#include<iostream>
#include<string>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include<sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <ctime>
#include <openssl/sha.h>
#include <cmath>
#include "sv_node.hpp"
#include "my570list.hpp"
#include "cs570.h"

//extern FILE *Log;
extern struct timeval tim;
extern string extfile;
extern string LogLocation;
extern string NodeHome;
extern string FilesHome;
extern string FilesRef;
//extern FILE* status;
extern char* HomeDir1;
extern char* LogFilename1;
extern char* UOIDstr;
extern char hostname[512];
//extern My570List* EventQ;
extern My570List* SocketList;
extern ini_info* i1;
extern unsigned int FileSizePrint;
extern Store_Elem* St_Elem;

extern pthread_mutex_t SocketList_lock;
extern pthread_mutex_t EventQ_lock;
extern pthread_mutex_t GlobalList_lock;
extern pthread_cond_t EventQ_cv;
extern pthread_mutex_t PrintLock;
extern pthread_mutex_t DBaseLock;
extern pthread_mutex_t NeighborList_lock; //= PTHREAD_MUTEX_INITIALIZER;
extern pthread_mutex_t status_lock;
extern pthread_mutex_t nam_lock;
extern pthread_mutex_t log_lock;
extern void InitRandom();
extern pthread_mutex_t CacheList_lock;
extern pthread_mutex_t PermList_lock;

My570List* DBase = new My570List();
My570List* nam = new My570List();
extern My570List* NeighborList;
list<Boot_Elem*> CacheList;
//extern pthread_mutex_t CacheList_lock;
extern list<GlobalList_Elem*> GlobalList;
int Catch;    
extern int counter; 
extern unsigned char *node_instance_id;
extern bool Duplicate;
extern int dupGlobal;


extern My570List* kwrdList;
extern My570List* nameList;
extern My570List* sha1List;
extern My570List* nonceList;
extern My570List* fileidList;


using namespace std;

void *Process_func(void *threadarg)
{
	
	
	//----------------- READING ALL BUT 1 BYTE
	int numBytes=0;
	int mySocket=0;
	mySocket = (int)threadarg;
	unsigned char *readBuf = new unsigned char[512];
	for (int it3 = 0;it3<45 ;it3++ )
		{
			if ((numBytes = read(mySocket,&readBuf[it3], 1))==-1)
			{
			//	perror("read");
			}
		}

    //----------------------------------------

	//--------------------- READING INTO FLOOD ELEM AND PUTTING INTO CORRECSPONDING EVENT QUEUE
	Flood_Elem *fd_obj = new Flood_Elem();
	fd_obj->MessageType = JNRQ;
	fd_obj->UOID = new unsigned char[20];
	fd_obj->respUOID = new unsigned char[20];
	memcpy(fd_obj->UOID,&readBuf[0],20);  
	memcpy(&(fd_obj->TTL),&readBuf[20],1);
	memcpy(&(fd_obj->HostLocation),&readBuf[26],4);
	memcpy(&(fd_obj->Port),&readBuf[30],2);
	fd_obj->TTL = (unsigned char)(((int)fd_obj->TTL)- 1);

//---------------------------------------------- RESET----------------------------------------------------//
	pthread_mutex_lock(&log_lock);
	FILE *Log1 = fopen(LogLocation.c_str(),"a");
	if(Log1==NULL)
	{
		cerr<<"Log file can not be opened. The program will continue without logging."<<endl;
	}else{
	gettimeofday(&tim,NULL);
	fprintf(Log1,"r %10ld.%03d nunki.usc.edu_%d JNRQ %d ",(tim.tv_sec),(int)((tim.tv_usec)/1000),fd_obj->Port,(int)(fd_obj->TTL));
		for(int pr=16;pr<20;pr++){fprintf(Log1,"%02x",(fd_obj->UOID)[pr]);}
	fprintf(Log1," %d nunki.usc.edu\n",fd_obj->Port);
	fflush(Log1);
	}
	fclose(Log1);
	pthread_mutex_unlock(&log_lock);
	//---------------------------------------------------------------------------------------------------------//


	list<Flood_Elem*>* EventQ = new list<Flood_Elem*>;
	GlobalList_Elem *Gelem = new GlobalList_Elem();
	Gelem->UOID = new unsigned char[20];
	Gelem->ListP = *EventQ;
	Gelem->Port =  fd_obj->Port;
	Gelem->Temp = 1;
	Gelem->Socket=mySocket;
	memcpy(Gelem->UOID,fd_obj->UOID,20);

	pthread_mutex_lock(&GlobalList_lock);
	GlobalList.push_back(Gelem);
	dupGlobal = eval_Global();
	pthread_mutex_unlock(&GlobalList_lock);
	
	list<GlobalList_Elem*>::iterator ite;


	//----------------------------------------------------------------------------------------
	list<GlobalList_Elem*>::iterator it;
	pthread_mutex_lock(&GlobalList_lock);
	for (it =GlobalList.begin();it!=GlobalList.end();it++ )
	{
		GlobalList_Elem *g1 = NULL;
		g1 = (GlobalList_Elem*) (*it);
		if ((*it)!=NULL)
		{
			if (g1->Temp != 1 && g1->Temp != 2)
			{
				//cout<<"Flooding to "<<g1->Port<<endl;
			pthread_mutex_lock(&g1->EventQlock);
			(g1->ListP).push_back(fd_obj);
			pthread_mutex_unlock(&g1->EventQlock);
			pthread_cond_broadcast(&g1->EventQ_cv);
			}
		}

	}
	
	pthread_mutex_unlock(&GlobalList_lock);
	
//____________________________________SENDING SELF RESPONSE----------------------BEGIN----------------------//	
	Flood_Elem *fd_obj2 = new Flood_Elem();
	fd_obj2->UOID = new unsigned char[20];
	fd_obj2->respUOID = new unsigned char[20];
	fd_obj2->MessageType = JNRS;
	fd_obj2->Port = fd_obj->Port;
	fd_obj2->respPort = i1->Port;
	for (int iter = 0;iter<20;iter++)
	{
		fd_obj2->UOID[iter] = fd_obj->UOID[iter];
		fd_obj2->respUOID[iter] = UOIDstr[iter];
	}
	fd_obj2->HostLocation = i1->Location;
	fd_obj2->Distance = (unsigned int)abs((int)(i1->Location) - (int)(fd_obj->HostLocation));
	int i=30;
	if(i1->TTL==0){fd_obj2->TTL=(unsigned char)i;}else{fd_obj2->TTL=(unsigned char)i1->TTL;}
				
	unsigned char *writeBuf = new unsigned char[512];
	unsigned char Reserved = (unsigned char)0;
	unsigned int DataLength = 39;
	memcpy(&writeBuf[0],&(fd_obj2->MessageType),1);
	memcpy(&writeBuf[1],fd_obj2->respUOID,20);
	memcpy(&writeBuf[21],&(fd_obj2->TTL),1);
	memcpy(&writeBuf[22],&Reserved,1);
	memcpy(&writeBuf[23],&DataLength,4);
	memcpy(&writeBuf[27],fd_obj2->UOID,20);
	memcpy(&writeBuf[47],&(fd_obj2->Distance),4);
	memcpy(&writeBuf[51],&(fd_obj2->respPort),2);
	memcpy(&writeBuf[53],&hostname,13);
	for (int it = 0;it<27 ;it++ )
	{
		if (write(mySocket,&writeBuf[it],1)==-1)
			{
			//	perror("beaconconnect: write");
				exit(1);
			}
	}
	for (int it5 = 27;it5<27+39; it5++ )
	{
		if (write(mySocket,&writeBuf[it5],1)==-1)
		{
//			perror("beaconconnect: write");
			exit(1);
		}	
	}

	//---------------------------------------------- RESET----------------------------------------------------//
	pthread_mutex_lock(&log_lock);
	FILE *Log = fopen(LogLocation.c_str(),"a");
	if(Log==NULL)
	{
		cerr<<"Log file can not be opened. The program will continue without logging."<<endl;
	}else{
	gettimeofday(&tim,NULL);
	fprintf(Log,"s %10ld.%03d nunki.usc.edu_%d JNRS %d ",(tim.tv_sec),(int)((tim.tv_usec)/1000),fd_obj2->Port,(int)(fd_obj2->TTL));
		for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(fd_obj2->respUOID)[pr]);}
		fprintf(Log," ");
		for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(fd_obj2->UOID)[pr]);}
	fprintf(Log," %d %d nunki.usc.edu\n",fd_obj2->Distance,fd_obj2->respPort);
	fflush(Log);
	}
	fclose(Log);
	pthread_mutex_unlock(&log_lock);
	//---------------------------------------------------------------------------------------------------------//
//____________________________________SENDING SELF RESPONSE----------------------END----------------------//	

	while(1){
	Flood_Elem *fd_obj1 = new Flood_Elem();
	list<Flood_Elem*>* locEventQ1 = new list<Flood_Elem*>;
	fd_obj1->UOID = new unsigned char[20];
	fd_obj1->respUOID = new unsigned char[20];
	pthread_mutex_lock(&Gelem->EventQlock);
	
	if ((Gelem->ListP).size()==0)
	{
		pthread_cond_wait(&(Gelem->EventQ_cv),&(Gelem->EventQlock));
	}
	
	pthread_mutex_unlock(&Gelem->EventQlock);
	pthread_mutex_lock(&DBaseLock);	
	*locEventQ1 = Gelem->ListP;
	fd_obj1 = (Flood_Elem*)((*locEventQ1).front());
	DBase->Append((void *)fd_obj1->UOID);
	pthread_mutex_unlock(&DBaseLock);

	pthread_mutex_lock(&Gelem->EventQlock);	
	(Gelem->ListP).pop_front();
	pthread_mutex_unlock(&Gelem->EventQlock);
	if(fd_obj1->MessageType == JNRS){
	if ((int)fd_obj1->TTL !=0)
	{
		unsigned char *writeBuf1 = new unsigned char[512];
		unsigned char Reserved = (unsigned char)0;
		unsigned int DataLength = 39;
		if (fd_obj1->MessageType == JNRS)
		{
			
			memcpy(&writeBuf1[0],&(fd_obj1->MessageType),1);
			memcpy(&writeBuf1[1],fd_obj1->respUOID,20);
			memcpy(&writeBuf1[21],&(fd_obj1->TTL),1);
			memcpy(&writeBuf1[22],&Reserved,1);
			memcpy(&writeBuf1[23],&DataLength,4);
			memcpy(&writeBuf1[27],fd_obj1->UOID,20);
			memcpy(&writeBuf1[47],&(fd_obj1->Distance),4);
			memcpy(&writeBuf1[51],&(fd_obj1->respPort),2);
			memcpy(&writeBuf1[53],&hostname,13);
			for (int it = 0;it<27 ;it++ )
			{
				if (write(mySocket,&writeBuf1[it],1)==-1)
					{
//						perror("beaconconnect: write");
						exit(1);
					}
			}
			for (int it5 = 27;it5<27+39; it5++ )
			{
				if (write(mySocket,&writeBuf1[it5],1)==-1)
				{
//					perror("beaconconnect: write");
					exit(1);
				}	
			}

			//---------------------------------------------- RESET----------------------------------------------------//
			pthread_mutex_lock(&log_lock);
			FILE *Log = fopen(LogLocation.c_str(),"a");
			if(Log==NULL)
			{
			cerr<<"Log file can not be opened. The program will continue without logging."<<endl;
			}else{
			gettimeofday(&tim,NULL);
			fprintf(Log,"s %10ld.%03d nunki.usc.edu_%d JNRQ %d ",(tim.tv_sec),(int)((tim.tv_usec)/1000),fd_obj1->Port,(int)(fd_obj1->TTL));
			for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(fd_obj1->UOID)[pr]);}
			fprintf(Log," %d nunki.usc.edu\n",fd_obj1->Port);
			fflush(Log);
			}
			fclose(Log);
			pthread_mutex_unlock(&log_lock);
			//---------------------------------------------------------------------------------------------------------//

			}
			pthread_mutex_lock(&PrintLock);
			pthread_mutex_unlock(&PrintLock);
		}//end if ttl !=0
		}//end if msg type == JNRS
	}//end while
	//cout<<"Inside process thread+++++++++++++++++++++++"<<endl;	exit(1);

	return 0;
}


//----------------------------------------- READ THREAD TO BE DONE -------------------------------------------------//

void *readthread(void *threadarg)
{
	//cout<<"**********************************************************8"<<endl;
	int mySocket = 0;
	int numBytes=0;
	GlobalList_Elem* Gelem = (GlobalList_Elem *)threadarg;
	mySocket = Gelem->Socket; 
	int RemainingCache = i1->CacheSize;
	int neighborsTemp;
	while(1){
		//cout<<"Here"<<endl;
		neighborsTemp=0;
		Catch = 1;
		int checkdel=0;
		unsigned char *readBuf = new (nothrow) unsigned char[512];
		memset(readBuf,0,512);
		for(int ih=0;ih<27;ih++)
		{
			if((numBytes=read(mySocket,&readBuf[ih], 1))==-1){
  //             perror("read");
						//cout<<"CheckRead1:"<<errno<<endl;
			}
		}
		if(numBytes==0)
		{
			usleep(100);
			continue;
		}
		struct HEADER h1;
		memset(&h1,0,sizeof h1);
		h1.UOID = new unsigned char[20];	   
		memcpy(&h1.MessageType,&readBuf[0],1);
		memcpy(h1.UOID,&readBuf[1],20);
		memcpy(&h1.TTL,&readBuf[21],1);
		memcpy(&h1.Reserved,&readBuf[22],1);
		memcpy(&h1.DataLength,&readBuf[23],4);

		if (h1.MessageType==SHRS)
		{
			for (unsigned int it3 = 27;it3<27+h1.DataLength;it3++ )
			{
				if ((numBytes = read(mySocket,&readBuf[it3], 1))==-1)
				{
				//		perror("read");
						
				}
			}
			//cout<<"SHRS RECEIVED"<<endl;
		}
		if (h1.MessageType==SHRQ)
		{
			Flood_Elem *fd_obj = new Flood_Elem();
			memset(fd_obj,0,sizeof(Flood_Elem));
			fd_obj->UOID = new unsigned char[20];
			fd_obj->Sha1 = new char[40];
			fd_obj->Nonce = new char[40];
			fd_obj->MessageType = h1.MessageType;
			memcpy(fd_obj->UOID,h1.UOID,20);
/*			pthread_mutex_lock(&DBaseLock);
			DBase->Append((void *)(fd_obj->UOID));
			pthread_mutex_unlock(&DBaseLock);
*/			if(i1->TTL==0){fd_obj->TTL=(unsigned char)30;}else{fd_obj->TTL=(unsigned char)i1->TTL;}
			fd_obj->TTL = (unsigned char)min((int)fd_obj->TTL,((int)(h1.TTL)-1));

			for (unsigned int it3 = 27;it3<27+h1.DataLength;it3++ )
			{
				if ((numBytes = read(mySocket,&readBuf[it3], 1))==-1)
				{
				//		perror("read");
						
				}
			}
			unsigned char tempType;
			memcpy(&tempType,&readBuf[27],1);
			int searchIndex=0;
			if (tempType==srchFileName)
			{
				fd_obj->Distance=1;
				fd_obj->FileName = new char[h1.DataLength-1];
				memcpy(fd_obj->FileName,&readBuf[28],h1.DataLength-1);
				string nameFile = string(fd_obj->FileName);
				searchIndex=sv_searchName(nameFile);
				//cout<<nameFile<<" "<<searchIndex<<endl;
			}
			if (tempType==srchSha1)
			{
				fd_obj->Distance=2;
				fd_obj->Sha1 = new char[h1.DataLength-1];
				memcpy(fd_obj->Sha1,&readBuf[28],h1.DataLength-1);
				string sha1 = string(fd_obj->Sha1);
				searchIndex=sv_searchSha1(sha1);
				//cout<<sha1<<" "<<searchIndex<<endl;
			}
			if (tempType==srchKeys)
			{
				fd_obj->Distance=3;
				fd_obj->Nonce = new char[h1.DataLength-1];
				memcpy(fd_obj->Nonce,&readBuf[28],h1.DataLength-1);
				string keys = string(fd_obj->Nonce);
				searchIndex=sv_searchKeys(keys);
				//cout<<keys<<" "<<searchIndex<<endl;
			}
				if (searchIndex!=0)
				{
				
					int memMap = 100;
					Flood_Elem *fd_obj1 = new Flood_Elem();
					memset(fd_obj1,0,sizeof(Flood_Elem));
					fd_obj1->UOID = new unsigned char[20];
					fd_obj1->respUOID = new unsigned char[20];

					if(i1->TTL==0){fd_obj1->TTL=(unsigned char)30;}else{fd_obj1->TTL=(unsigned char)i1->TTL;}
					fd_obj1->TTL = (unsigned char)min((int)fd_obj1->TTL,((int)(h1.TTL)-1));
					fd_obj1->MessageType = SHRS;
					fd_obj1->respPort = i1->Port;
					memcpy(fd_obj1->respUOID,(GetUOID(node_instance_id,"msg")),20);
					memcpy(fd_obj1->UOID,h1.UOID,20);
					fd_obj1->Distance=fd_obj->Distance;
					fd_obj1->password=searchIndex;
					memMap = memcmp(fd_obj1->respUOID,fd_obj1->UOID,20);
					if (memMap!=0)
					{
						//cout<<"Sending SHRS back to "<<ntohs(peer.sin_port)<<endl;
						pthread_mutex_lock(&Gelem->EventQlock);
						(Gelem->ListP).push_back(fd_obj1);
						pthread_cond_signal(&Gelem->EventQ_cv);		
						pthread_mutex_unlock(&Gelem->EventQlock);
					}else;
				//delete fd_obj1;

				}else;//end if searchIndex!=0

				//delete fd_obj;
		}
		if (h1.MessageType==DELT)
		{
			socklen_t len;
			struct sockaddr_in peer;
			len = sizeof peer;
			getpeername(mySocket, (struct sockaddr*)&peer, &len);

			int FileSize = h1.DataLength-(84);
			Flood_Elem *fd_obj = new Flood_Elem();
			memset(fd_obj,0,sizeof(Flood_Elem));
			fd_obj->UOID = new unsigned char[20];
			fd_obj->FileName = new char[FileSize];
			fd_obj->Sha1 = new char[40];
			fd_obj->Nonce = new char[40];
			fd_obj->MessageType = h1.MessageType;
			memcpy(fd_obj->UOID,h1.UOID,20);
			pthread_mutex_lock(&DBaseLock);
			DBase->Append((void *)(fd_obj->UOID));
			pthread_mutex_unlock(&DBaseLock);
				if(i1->TTL==0){fd_obj->TTL=(unsigned char)30;}else{fd_obj->TTL=(unsigned char)i1->TTL;}
				fd_obj->TTL = (unsigned char)min((int)fd_obj->TTL,((int)(h1.TTL)-1));

			for (unsigned int it3 = 27;it3<27+h1.DataLength;it3++ )
			{
				if ((numBytes = read(mySocket,&readBuf[it3], 1))==-1)
				{
				//		perror("read");
						
				}
			}

			memcpy(fd_obj->FileName,&readBuf[27],FileSize);
			memcpy(fd_obj->Sha1,&readBuf[27+FileSize],40);
			memcpy(fd_obj->Nonce,&readBuf[27+FileSize+40],40);
			memcpy(&fd_obj->password,&readBuf[27+FileSize+80],4);
		//	cout<<fd_obj->FileName<<endl;			
		//	cout<<fd_obj->Sha1<<endl;
		//	cout<<fd_obj->Nonce<<endl;
		//	cout<<fd_obj->password<<endl;
			checkdel = sv_delete(fd_obj->FileName,fd_obj->Sha1,fd_obj->Nonce,fd_obj->password);
			Catch=1;
			pthread_mutex_lock(&log_lock);
			FILE *Log = fopen(LogLocation.c_str(),"a");
			if(Log==NULL)
			{
			cerr<<"Log file can not be opened. The program will continue without logging."<<endl;
			}else{
			gettimeofday(&tim,NULL);
			fprintf(Log,"r %10ld.%03d nunki.usc.edu_%d DELT %d ",(tim.tv_sec),(int)((tim.tv_usec)/1000),ntohs(peer.sin_port),(int)(h1.TTL));
			for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(h1.UOID)[pr]);}
			fprintf(Log,"\n");
			fflush(Log);
			}
			fclose(Log);
			pthread_mutex_unlock(&log_lock);	
/*			pthread_mutex_lock(&DBaseLock);
			Catch = eval_DBase();
			pthread_mutex_unlock(&DBaseLock);
			if (Catch == 1)
			{
				list<GlobalList_Elem*>::iterator it;
				pthread_mutex_lock(&GlobalList_lock);
				for (it =GlobalList.begin();it!=GlobalList.end();it++ )
				{
					GlobalList_Elem *g1 = NULL;
					g1 = (GlobalList_Elem*) (*it);
					if ((*it)!=NULL)
					{
						if (g1->Temp != 1 && g1->Temp!=2 && g1->Temp!=3 && g1->Temp!=4 && g1->Temp!=5 && g1->Temp!=7 && g1->Temp!=8 && g1->Temp!=9)
						{
						
							pthread_mutex_lock(&PrintLock);
							pthread_mutex_unlock(&PrintLock);
							pthread_mutex_lock(&g1->EventQlock);
							(g1->ListP).push_back(fd_obj);
							pthread_mutex_unlock(&g1->EventQlock);
							pthread_cond_broadcast(&g1->EventQ_cv);
						}
					}

				}
				pthread_mutex_unlock(&GlobalList_lock);
			}
*/			//delete fd_obj;
		}
	//---------------------STOR received---------------------------BEGIN---------------------------//
		if (h1.MessageType==STOR)
		{

		//	cout<<"Received Store request"<<endl;
//			int sumBytes=0;
			Flood_Elem *fd_obj = new Flood_Elem();
			memset(fd_obj,0,sizeof(Flood_Elem));
			fd_obj->UOID = new unsigned char[20];
			fd_obj->MessageType = h1.MessageType;
			memcpy(fd_obj->UOID,h1.UOID,20);
			pthread_mutex_lock(&DBaseLock);
			DBase->Append((void *)(fd_obj->UOID));
			Catch=1;
		//	cout<<"BEFORE DBase"<<endl;
			//print_DBase();
			Catch = eval_DBase();
		//	cout<<"AFTER DBase"<<endl;

			pthread_mutex_unlock(&DBaseLock);
				if(i1->TTL==0){fd_obj->TTL=(unsigned char)30;}else{fd_obj->TTL=(unsigned char)i1->TTL;}
				fd_obj->TTL = (unsigned char)min((int)fd_obj->TTL,((int)(h1.TTL)-1));
			
			for (unsigned int it3 = 27;it3<31;it3++ )
			{
				if ((numBytes = read(mySocket,&readBuf[it3], 1))==-1)
				{
				//		perror("read");
						
				}

			}
			
		//	cout<<"STOR read"<<endl;
			socklen_t len;
			struct sockaddr_in peer;
			len = sizeof peer;
			getpeername(mySocket, (struct sockaddr*)&peer, &len);
//			pthread_mutex_lock(&PrintLock);
			Store_Elem* St_Elem = new Store_Elem();
			memset(St_Elem,0,sizeof(Store_Elem));
			memcpy(&St_Elem->MetaSize,&readBuf[27],4);
			unsigned int FileSize=0;
			FileSize=h1.DataLength-4-St_Elem->MetaSize;
			unsigned int writebytes=0;
			FILE *pf3 = fopen("tempmeta","wb");
			for (unsigned int it3 = 31;it3<31+(St_Elem->MetaSize);it3++ )
			{
				if ((numBytes = read(mySocket,&readBuf[it3], 1))==-1)
				{
				//		perror("read");
						
				}
				writebytes=fwrite(&readBuf[it3],1,1,pf3);
			}
		//	cout<<"Metafile read"<<endl;
			fclose(pf3);
		//	cout<<St_Elem->MetaSize<<" "<<FileSize<<endl;
			//-------------------READING ACTUAL FILE------------------------------BEGIN----------//
			FILE *pf4 = fopen("tempfile","wb");
		//	cout<<"READING FILE"<<endl;

			unsigned int dsz = FileSize;
			unsigned int countd = dsz/8192;
			
			unsigned int actdsz= dsz;

			if(countd>=1 && (dsz%8192)!=0){
				countd=countd+1;
			}else{
				if(countd==0){
					countd=1;
				}else{
					countd=dsz/8192;
				}
			}
			unsigned int buf_cou=0;
			for(unsigned int dcount=0;dcount<countd;dcount++){

				if(actdsz>=8192){
					buf_cou=8192;
				}else{
					buf_cou=actdsz;
				}
				actdsz = actdsz - 8192;
			unsigned char* FileBuf = (unsigned char*)malloc(8192);
			memset(FileBuf,0,8192);

			size_t bytes_write;
			for (unsigned int it3 = 0;it3<buf_cou;it3++)
			{
				if ((numBytes = read(mySocket,&FileBuf[it3], 1))==-1)
				{
					//		perror("read");						
				}

				bytes_write=fwrite(&FileBuf[it3],1,1,pf4);
			}
			
       buf_cou=0;
	   free(FileBuf);
	   }//count for loop
	   fclose(pf4);
			//-------------------READING ACTUAL FILE------------------------------END----------//

			fclose(pf4);
		//	cout<<"After reading file"<<endl;
			pthread_mutex_lock(&log_lock);
			FILE *Log = fopen(LogLocation.c_str(),"a");
			if(Log==NULL)
			{
			cerr<<"Log file can not be opened. The program will continue without logging."<<endl;
			}else{
			gettimeofday(&tim,NULL);
			fprintf(Log,"r %10ld.%03d nunki.usc.edu_%d STOR %d ",(tim.tv_sec),(int)((tim.tv_usec)/1000),ntohs(peer.sin_port),(int)(h1.TTL));
			for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(h1.UOID)[pr]);}
			fprintf(Log,"\n");
			fflush(Log);
			}
			fclose(Log);
			pthread_mutex_unlock(&log_lock);	

			if (Catch == 1)
			{

				float StoreProb = 0.0;
				InitRandom();
				StoreProb = drand48();
			if ((i1->StoreProb >= StoreProb))
			{
			//	cout<<"PROB COND SATISFIED"<<endl;
	//			string NodeHome;
	//			string FilesHome;
	//			string FilesRef;
				string FileName;
				string MetaName;

				char myCurrName[100];
				char myFileName[100];
				char ch;
				int k=0;
				string metaNames;
				//cout<<"BEFORE BOOTELEM"<<endl;
				//Boot_Elem *Cache_Belem = (Boot_Elem *)malloc(sizeof (Boot_Elem));
				//cout<<"AFTER BOOTELEM"<<endl;
				unsigned int temMetaSize = St_Elem->MetaSize;
				//cout<<temMetaSize<<endl;
				if (((temMetaSize)+FileSize)>(unsigned)((i1->CacheSize)*1024))
				{
					//cout<<"FILESZ>CACHESZ"<<endl;
					//drop it and remove the tempfiles
				}
				else{
						//---------GETTING INDEX-------------//
			//					cout<<"GETTING INDEX"<<endl;
				
		//					NodeHome = (string(HomeDir1)).substr(0,(int)strlen(HomeDir1)-1);
		//					 FilesHome = NodeHome + "/files";

                             struct stat mystat;
							 if(stat(FilesHome.c_str(),&mystat) == 0){
								//FilesRef= FilesHome + "/FilesRef";
								//cout<<"Directory present"<<endl;
							 }else{
								int zero;
								zero=0;
								mkdir(FilesHome.c_str(),00777);
								//FilesRef= FilesHome + "/FilesRef";
								FILE *fp2 = fopen(FilesRef.c_str(),"w");
								fprintf(fp2,"%d",zero);
								fclose(fp2);
								//cout<<"Directory created"<<endl;
							}
							
						FILE *fp3 = fopen(FilesRef.c_str(),"r");
						fgets(myFileName,100,fp3);
						
						k=atoi(myFileName);
						sprintf(myCurrName,"%d",k+1);
						FileName = FilesHome +"/"+string(myCurrName) +".data";
						MetaName = FilesHome +"/"+string(myCurrName) +".meta";

						remove(FilesRef.c_str());
						FILE *fp4 = fopen(FilesRef.c_str(),"w");
						fprintf(fp4,"%d",k+1);
						fclose(fp4);
					//	Cache_Belem->index = k+1;
						//cout<<"GOT FILENAME"<<endl;
						//cout<<"Metasize: "<<St_Elem->MetaSize<<endl;
						//cout<<FileName<<endl;
						//cout<<MetaName<<endl;
					if ((St_Elem->MetaSize)>(unsigned)((RemainingCache)*1024))
					{
	/*					//cout<<"FILESIZE>REMAININGCACHE"<<endl;
						//do LRU and then STORE
						string rmFileName;
						string rmMetaName;
						Boot_Elem* St_Boot= new Boot_Elem();
					//	pthread_mutex_lock(&CacheList_lock);
					//	St_Boot= CacheList.front();
					//	CacheList.pop_front();
					//	pthread_mutex_unlock(&CacheList_lock);
			//			cout<<St_Boot->index<<endl;
						char rmFile[100];
						sprintf(rmFile,"%d",St_Boot->index);
						rmFileName = FilesHome+ "/"+string(rmFile) +".data";
						rmMetaName = FilesHome+ "/"+string(rmFile) +".meta";
						struct stat st1,st2;
						stat(rmFileName.c_str(),&st1);
						stat(rmMetaName.c_str(),&st2);
						unsigned int rmfsize = st1.st_size;
						unsigned int rmmetasize = st2.st_size;
						remove(rmFileName.c_str());
						remove(rmMetaName.c_str());
						RemainingCache = RemainingCache-(rmfsize+rmmetasize);
						while ((St_Elem->MetaSize)>(unsigned)((RemainingCache)*1024))
						{
					//		pthread_mutex_lock(&CacheList_lock);
					//		St_Boot= CacheList.front();
					//		CacheList.pop_front();
					//		pthread_mutex_unlock(&CacheList_lock);
						//	cout<<St_Boot->index<<endl;
							char rmFile[100];
							sprintf(rmFile,"%d",St_Boot->index);
							rmFileName = FilesHome+ "/"+string(rmFile) +".data";
							rmMetaName = FilesHome+ "/"+string(rmFile) +".meta";
							struct stat st1,st2;
							stat(rmFileName.c_str(),&st1);
							stat(rmMetaName.c_str(),&st2);
							unsigned int rmfsize = st1.st_size;
							unsigned int rmmetasize = st2.st_size;
							remove(rmFileName.c_str());
							remove(rmMetaName.c_str());
							RemainingCache = RemainingCache-(rmfsize+rmmetasize);

						}//end while loop
*/
					}//end if size>RemainingCache
			//		cout<<"Before permanent"<<endl;
					  FILE *fp1= fopen("tempfile","rb");
						  FILE *fp5 = fopen(FileName.c_str(),"wb");

						  while(!feof(fp1)){
							  ch = fgetc(fp1);
							  if(!feof(fp1))
                              fputc(ch,fp5);

						  }// while fp1

						  fclose(fp1);
						  fclose(fp5);
						  
							FILE *fp6 = fopen("tempmeta","rb");
							FILE *fp7 = fopen(MetaName.c_str(),"wb");
						  while(!feof(fp6)){
							  ch = fgetc(fp6);
							  if(!feof(fp6))
                              fputc(ch,fp7);

						  }// while fp1

						  fclose(fp6);
						  fclose(fp7);
	
						//--------------------------------- Chaita code-----------------------------BEGIN//

						int eq= 0;
						char bufMeta[100];
						char bufMeta1[100];
						char bufsha1[100];
						char bufbitv1[300];
						char bufnonce1[100];
						FILE *MFile = fopen("tempmeta","r");
						fgets(bufMeta,100,MFile);
						fgets(bufMeta1,100,MFile);
						fgets(bufsha1,100,MFile);						
						fgets(bufsha1,100,MFile);
						fgets(bufnonce1,100,MFile);
						fgets(bufbitv1,100,MFile);
						fgets(bufbitv1,100,MFile);
						fgets(bufbitv1,300,MFile);
                        string ParseMetaSha1 = string(bufsha1);
						eq = ParseMetaSha1.find_first_of("=");
                        string MetaSha1 =  ParseMetaSha1.substr(eq+1,ParseMetaSha1.length()-eq-2);

						unsigned char* hexstring = (unsigned char*)malloc(20);
						unsigned char temp1;
						unsigned char temp2;
						int ik=0;
						for(int i=0;i<40;i=i+2)
						{
							temp1=tohex(MetaSha1[i]);
							temp2=tohex(MetaSha1[i+1]);

							temp1=temp1<<4;

							hexstring[ik]=temp1 | temp2;
							ik=ik+1;
							
						}
						string ParseMetaNonce1 = string(bufnonce1);
						eq = ParseMetaNonce1.find_first_of("=");
                        string MetaNonce1 =  ParseMetaNonce1.substr(eq+1,ParseMetaNonce1.length()-eq-2);
						unsigned char* hexstring2 = (unsigned char*)malloc(20);
						unsigned char temp5;
						unsigned char temp6;
						int jk=0;
						for(int i=0;i<40;i=i+2)
						{
							temp5=tohex(MetaNonce1[i]);
							temp6=tohex(MetaNonce1[i+1]);

							temp5=temp5<<4;

							hexstring2[jk]=temp5 | temp6;
							jk=jk+1;
							
						}
                        string ParseMetaBitV1 = string(bufbitv1);
						eq = ParseMetaBitV1.find_first_of("=");
                        string MetaBitV1 =  ParseMetaBitV1.substr(eq+1,ParseMetaBitV1.length()-eq-2);

						unsigned char* hexstring1 = (unsigned char*)malloc(128);
						unsigned char temp3;
						unsigned char temp4;
			 

						int ik1=0;
						for(int i=0;i<256;i=i+2)
						{
							temp3=tohex(MetaBitV1[i]);
							temp4=tohex(MetaBitV1[i+1]);

							temp3=temp3<<4;

							hexstring1[ik1]=temp3 | temp4;
							ik1=ik1+1;
							
						}
			//			cout<<"BITVECTOR in HEX: "<<endl;
			//			for (int i=0;i<128;i++ )
			////			{
				//			printf("%02x",hexstring1[i]);
				//		}  cout<<endl;
//						memcpy(belem->Key,hexstring1,128);					
					//--------------------------------- Chaita code-------------------------------END//
						
						string ParseMeta = string(bufMeta1);
						eq = ParseMeta.find_first_of("=");

						string MetaFileName = ParseMeta.substr(eq+1,ParseMeta.length()-eq-2);
//						cout<<MetaFileName<<endl;
						fclose(MFile);
						ParseMeta.erase();
						MetaBitV1.erase();
						ParseMetaBitV1.erase();
						MetaNonce1.erase();
						ParseMetaNonce1.erase();
						MetaSha1.erase();
						ParseMetaSha1.erase();
					//	Cache_Belem->FileName = new char[MetaFileName.length()];
					//	strcpy(Cache_Belem->FileName,MetaFileName.c_str());
						St_Elem->FileName = new char[FileName.length()];
						memset(St_Elem->FileName,0,FileName.length());
						St_Elem->MetaName = new char[MetaName.length()];
						memset(St_Elem->MetaName,0,MetaName.length());
						strcpy(St_Elem->FileName,FileName.c_str());
						strcpy(St_Elem->MetaName,MetaName.c_str());

						//strcpy(St_Elem->MetaName,MetaFileName.c_str());
						Boot_Elem *belemN = new Boot_Elem();
						Boot_Elem *belemS = new Boot_Elem();
						Boot_Elem *belemK = new Boot_Elem();
						Boot_Elem *belemNo = new Boot_Elem();						  
						Boot_Elem* belemF = new Boot_Elem();
						memset(belemN,0,sizeof(Boot_Elem));
						memset(belemS,0,sizeof(Boot_Elem));
						memset(belemK,0,sizeof(Boot_Elem));
						memset(belemNo,0,sizeof(Boot_Elem));
						memset(belemK,0,sizeof(Boot_Elem));
						//---------------------- Append fileid to sha1List-------BEGIN//

	//cout<<"APPENDING ONTO LISTS"<<endl;
					
						belemF->index = k+1;
						belemN->index=k+1;
						belemS->index=k+1;
						belemK->index=k+1;
						belemNo->index=k+1;
					
		//				belemF->index = Cache_Belem->index;
		//				belemN->index=Cache_Belem->index;
		//				belemS->index=Cache_Belem->index;
		//				belemK->index=Cache_Belem->index;
		//				belemNo->index=Cache_Belem->index;
						belemNo->password=0;
						
						belemNo->Nonce = new unsigned char[20];
						belemN->FileName = new char[100];
						belemS->Sha1 = new unsigned char[20];
						belemK->Key = new unsigned char[128];
						belemF->FileId = new unsigned char[20];					
						unsigned char* myUD = new unsigned char[20];
						myUD = GetUOID(node_instance_id,"file");

						strcpy(belemN->FileName,MetaFileName.c_str());
						memcpy(belemS->Sha1,hexstring,20);
						memcpy(belemK->Key,hexstring1,128);
						memcpy(belemNo->Nonce,hexstring2,20);
						memcpy(belemF->FileId,myUD,20);
					//-------------------APPENDING ONTO LISTS----------------//
						pthread_mutex_lock(&PermList_lock);
			            nameList->Append((void*)belemN);
						sha1List->Append((void*)belemS);
			            kwrdList->Append((void*)belemK);
						nonceList->Append((void*)belemNo);
						fileidList->Append((void*)belemF);
						pthread_mutex_unlock(&PermList_lock);
					//-------------------APPENDING ONTO LISTS----------------end-------//
				//		cout<<"nameList: "<<endl;
				//		cout<<belemN->index<<endl;
				//		cout<<belemN->FileName<<endl;
						//exit(1);
		//				cout<<Cache_Belem->FileName<<endl;
		//				cout<<Cache_Belem->index<<endl;
//						pthread_mutex_lock(&CacheList_lock);
//						CacheList.push_back(Cache_Belem);
//						pthread_mutex_unlock(&CacheList_lock);

/*						Catch=1;
						pthread_mutex_lock(&DBaseLock);
						Catch = eval_DBase();
						pthread_mutex_unlock(&DBaseLock);
						if (Catch==1)
						{
						
*/					/*	list<GlobalList_Elem*>::iterator it;
						pthread_mutex_lock(&GlobalList_lock);
						for (it =GlobalList.begin();it!=GlobalList.end();it++ )
						{
							   GlobalList_Elem *g1 = NULL;
							   g1 = (GlobalList_Elem*) (*it);
							   if ((*it)!=NULL)
							   {
									   if (g1->Temp != 1 && g1->Temp!=2 && g1->Temp!=3 && g1->Temp!=4 && g1->Temp!=5 && g1->Temp!=8 && g1->Temp!=9 )
									   {
										   float FloodProb=0.0;
										   InitRandom();
										   FloodProb = drand48();

										if ((i1->NeighborStoreProb) >= FloodProb && i1->Port!= (*it)->Port)
										{
											  // cout<<"Keyboard Flooding STOR to "<<g1->Port<<endl;
											   pthread_mutex_lock(&g1->EventQlock);
											   (g1->ListP).push_back(fd_obj);
											   pthread_mutex_unlock(&g1->EventQlock);
											   pthread_cond_broadcast(&g1->EventQ_cv);
										}
									   }
							   }

						 }//end for loop
						 pthread_mutex_unlock(&GlobalList_lock);					
*///					delete belemN;
//					delete belemK;
//					delete belemF;
//					delete belemS;
				// }//end if catch=1
					}//end if size<CacheSize
								

			}else; //cout<<"PROB NT satisfied on RDTHREAD"<<endl;//end if storeprob<i1->storeprob
		//	exit(1);
			}//end if catch =1
			
		}




		//---------------------STOR received---------------------------END---------------------------//
		//-------------------------------KPAV RECEIVED------------------------------------------------------//
		if (h1.MessageType==KPAV)
		{

			
			socklen_t len;
			struct sockaddr_in peer;
			len = sizeof peer;
			getpeername(mySocket, (struct sockaddr*)&peer, &len);

			pthread_mutex_lock(&log_lock);
			FILE *Log = fopen(LogLocation.c_str(),"a");
			if(Log==NULL)
			{
			cerr<<"Log file can not be opened. The program will continue without logging."<<endl;
			}else{
			gettimeofday(&tim,NULL);
			fprintf(Log,"r %10ld.%03d nunki.usc.edu_%d KPAV %d ",(tim.tv_sec),(int)((tim.tv_usec)/1000),ntohs(peer.sin_port),(int)(h1.TTL));
			for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(h1.UOID)[pr]);}
			fprintf(Log,"\n");
			fflush(Log);
			}
			fclose(Log);
			pthread_mutex_unlock(&log_lock);	
		}
		//--------------------------KPAV RECEIVED END-------------------------------------------------------------//

		//-------------------------------KPAV RECEIVED------------------------------------------------------//
		if (h1.MessageType==NTFY)
		{
			Flood_Elem *ntfy_obj = new Flood_Elem();


			char* myBuf =  new char[2];
			for (int it=0;it<2;it++)
			{
				
				if ((numBytes = read(mySocket,&myBuf[it], 1))==-1){
	//			perror("read");
						//cout<<"CheckRead2:"<<errno<<endl;
				}
				//cout<<it<<endl;
				//cout<<myBuf[it]<<endl;
			}
			//cout<<numBytes<<endl;
			memcpy(&ntfy_obj->Port,&myBuf[0],2);
			//cout<<"rPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP"<<ntfy_obj->Port<<endl;
			//exit(1);
			socklen_t len;
			struct sockaddr_in peer;
			len = sizeof peer;
			getpeername(mySocket, (struct sockaddr*)&peer, &len);
			//cout<<"NOTIFYYYYYYYYYYYYYYYYYYYYYY"<<ntohs(peer.sin_port)<<endl;
			pthread_mutex_lock(&GlobalList_lock);
			//cout<<"KLJLKJLDSKJFLKJSF "<<rPort<<endl;
				 list<GlobalList_Elem*>::iterator it;
			for (it =GlobalList.begin();it!=GlobalList.end();it++ )
			{
				   GlobalList_Elem *g1 = NULL;
				   g1 = (GlobalList_Elem*) (*it);
					if (g1->Port == ntfy_obj->Port)
					{
			//			cout<<"Removing: "<<g1->Port<<endl;
						GlobalList.remove(g1);
					}
			}
			//print_GlobalList();
			pthread_mutex_unlock(&GlobalList_lock);

			pthread_mutex_lock(&log_lock);
			FILE *Log = fopen(LogLocation.c_str(),"a");
			if(Log==NULL)
			{
			cerr<<"Log file can not be opened. The program will continue without logging."<<endl;
			}else{
			gettimeofday(&tim,NULL);
			fprintf(Log,"r %10ld.%03d nunki.usc.edu_%d NTFY %d ",(tim.tv_sec),(int)((tim.tv_usec)/1000),ntohs(peer.sin_port),(int)(h1.TTL));
			for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(h1.UOID)[pr]);}
			fprintf(Log," shutdown\n");
			fflush(Log);
			}
			fclose(Log);
			pthread_mutex_unlock(&log_lock);	
		}
		//--------------------------KPAV RECEIVED END-------------------------------------------------------------//

		//-------------------------------------------------------------- STRS RECEIVED ON READ -------------------------BEGIN//

		if (h1.MessageType == STRS){
//			cout<<"status response received "<<endl;
			for (unsigned int it3 = 27;it3<27+h1.DataLength;it3++ )
			{
				if ((numBytes = read(mySocket,&readBuf[it3], 1))==-1)
				{
			//		perror("read");
					
				}
			}
			//cout<<"DataLength"<<h1.DataLength<<endl;
			Flood_Elem *fd_obj1 = new Flood_Elem();
			//cout<<"NumBytes: "<<numBytes<<endl;
			fd_obj1->UOID = new unsigned char[20];
			fd_obj1->respUOID = new unsigned char[20];
			fd_obj1->MessageType = h1.MessageType;
			memcpy(fd_obj1->respUOID,&readBuf[1],20);
			memcpy(fd_obj1->UOID,&readBuf[27],20);
			memcpy(&fd_obj1->respPort,&readBuf[49],2);
//			memcpy(&fd_obj1->Distance,


			int i=30;
			if(i1->TTL==0){fd_obj1->TTL=(unsigned char)i;}else{fd_obj1->TTL=(unsigned char)i1->TTL;}
			int memMap = 100;
			list<GlobalList_Elem*>::iterator it;
			int homeflag = 0;
			pthread_mutex_lock(&PrintLock);
			//print_GlobalList();
			pthread_mutex_unlock(&PrintLock);
			
			for (it =GlobalList.begin();it!=GlobalList.end();it++)
			{
				fd_obj1->Port = (*it)->Port;
			
					if (fd_obj1->Port == i1->Port && (*it)->Temp ==2)
					{
						homeflag=1;
						neighborsTemp=1;
//						cout<<"GOT STRS at home node"<<endl;
						break;
					}else if (fd_obj1->Port == i1->Port && (*it)->Temp ==8)
					{
						homeflag=1;
						neighborsTemp=2;
//						cout<<"Status files"<<endl;
						break;
					}else;
			}
//			cout<<homeflag<<endl;
		
			if (homeflag!=1)
			{
				for (it =GlobalList.begin();it!=GlobalList.end();it++)
				{
					if ((*it)->Temp!=2 && (*it)->Temp!=8)
					{
									
						memMap = memcmp(fd_obj1->UOID,((*it)->UOID),20);
						if (memMap == 0)
						{
							pthread_mutex_lock(&PrintLock);
							//cout<<"STRS sending Port: "<<fd_obj1->respPort<<endl;
							pthread_mutex_unlock(&PrintLock);
							if (fd_obj1->MessageType == STRS)
							{
								pthread_mutex_lock(&(*it)->EventQlock);
								((*it)->ListP).push_back(fd_obj1);
								pthread_cond_signal(&((*it)->EventQ_cv));
								pthread_mutex_unlock(&((*it)->EventQlock));
								pthread_mutex_unlock(&GlobalList_lock);

							}
						}else;
					}//end if temp	
				}//end for
			}//end homeflag
		if (neighborsTemp==1)
		{
            //---------------------------------------------- RESET----------------------------------------------------//
			pthread_mutex_lock(&log_lock);
			FILE *Log = fopen(LogLocation.c_str(),"a");
			if(Log==NULL)
			{
			cerr<<"Log file can not be opened. The program will continue without logging."<<endl;
			}else{
			gettimeofday(&tim,NULL);
			fprintf(Log,"r %10ld.%03d nunki.usc.edu_%d STRS %d ",(tim.tv_sec),(int)((tim.tv_usec)/1000),fd_obj1->respPort,(int)(h1.TTL));
			for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(fd_obj1->respUOID)[pr]);}
			fprintf(Log," ");
			for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(fd_obj1->UOID)[pr]);}
			fprintf(Log,"\n");
			fflush(Log);
			}
			fclose(Log);
			pthread_mutex_unlock(&log_lock);
			//---------------------------------------------------------------------------------------------------------//

			if (homeflag == 1)
			{
		//		cout<<"Got STRS 2 at home node"<<endl;
				unsigned short myNeighbor=0;
				int RecordIter=0;
				int RecordIter1=0;
				unsigned short nNeighbor=0;
				memcpy(&myNeighbor,&readBuf[49],2);
				memcpy(&RecordIter,&readBuf[64],4);
				memcpy(&RecordIter1,&readBuf[64],4);
				pthread_mutex_lock(&status_lock);
				FILE* status = fopen(extfile.c_str(),"a");
				if(status == NULL){cerr<<"Status file can not be generated. Please try again!"<<endl;}
				fprintf(status,"n -t * -s %u -c red -i black\n",myNeighbor);
				int myIter=68;
				while(RecordIter!=0){
		//			cout<<"RecordIter: "<<RecordIter<<endl;
					memcpy(&nNeighbor,&readBuf[myIter],2);
//					pthread_mutex_lock(&nam_lock);
				//	nam->Append((void*)nNeighbor);
				//	if (duplicateNode()==1)
				//	{
						fprintf(status,"n -t * -s %u -c red -i black\n",nNeighbor);
				//	}
//					pthread_mutex_unlock(&nam_lock);
					myIter=myIter+15;
					memcpy(&RecordIter,&readBuf[myIter],4);
					myIter=myIter+4;
					memset(&nNeighbor,0,2);
				}// while RecordIter

				int myIter1=68;
				while(RecordIter1!=0){
				
					memcpy(&nNeighbor,&readBuf[myIter1],2);
					fprintf(status,"l -t * -s %u -d %u -c blue\n",myNeighbor,nNeighbor);
					myIter1=myIter1+15;
					memcpy(&RecordIter1,&readBuf[myIter1],4);
					myIter1=myIter1+4;
					memset(&nNeighbor,0,2);

				}// while RecordIter
				fclose(status);
				pthread_mutex_unlock(&status_lock);
				counter++;

			
			}		//end if homeflag=1	
		}//end if neighborsTemp=1
		else if (neighborsTemp==2)
		{
			if (homeflag==1)
			{
			
			//int remBuf=h1.DataLength-(37);
			int FileSz=0;
/*			pthread_mutex_lock(&PrintLock);
			for (unsigned int i=27;i<27+h1.DataLength;i++)
			{
				cout<<readBuf[i];
			}cout<<endl;
			pthread_mutex_unlock(&PrintLock);
*/
            
		
			//----------------------------FILECOUNTER---------------------//
			int readcounter=0;
			int readit2 = 64;
			int FileSz2=0;
			while (1)
				{
				memcpy(&FileSz2,&readBuf[readit2],4);
				if(FileSz2==0)			break;
				readit2=readit2+4+FileSz2;
				readcounter=readcounter+1;
				}
            short neighborSt=0; 
				memcpy(&neighborSt,&readBuf[49],2);
					pthread_mutex_lock(&status_lock);
				FILE* stram = fopen(extfile.c_str(),"a");
				if(readcounter==0)
			    {
					fprintf(stram,"nunki.usc.edu:%d has no file\n",neighborSt);
			    }
				if(readcounter==1)
			    {
                fprintf(stram,"nunki.usc.edu:%d has %d file\n",neighborSt,readcounter);  
			    }
				if(readcounter>1)
				{
				fprintf(stram,"nunki.usc.edu:%d has %d files\n",neighborSt,readcounter);
				}
				fclose(stram);
//----------------------------FILECOUNTER---------------------end ---------//
			int readit =64;

	        while(1){
				memcpy(&FileSz,&readBuf[readit],4);
				if (FileSz==0)
				{
					break;
				}
					FILE* status = fopen(extfile.c_str(),"ab");
					if(status == NULL){cerr<<"Status file can not be generated. Please try again!"<<endl;}
					FILE *pf2 = fopen("tempread","ab");
				char ch;
				for (int i=0;i<=FileSz;i++)
				{
					ch = readBuf[readit+4+i];
					fputc(ch,pf2);
					fputc(ch,status);
				}
				fclose(status);
				fclose(pf2);

				pthread_mutex_unlock(&status_lock);
				pthread_mutex_lock(&PrintLock);
				//cout<<"FileSz"<<FileSz<<endl;
				pthread_mutex_unlock(&PrintLock);
				readit=readit+4+FileSz;
				//remBuf = remBuf-4-FileSz;
			}
//			exit(1);
/*			unsigned int writebytes=0;
			FILE *pf3 = fopen("tempSTRS","wb");
			for (unsigned int it3 = 68;it3<64+;it3++)
			{
				writebytes=fwrite(&readBuf[it3],1,1,pf3);
			}
			
			fclose(pf3);
*/		}//end if homeflag
		}//end if neighborsTemp=2
		}// if MessageType == STRS
        //-------------------------------------------------------------- STRS RECEIVED ON READ -------------------------BEGIN//  


        //-------------------------------------------------------------- STRQ RECEIVED ON  READ -----------------------------//
		if(h1.MessageType == STRQ)
		{
			if ((numBytes = read(mySocket,&readBuf[27], 1))==-1){
			//	perror("read");
			}      
			char statustype;
				socklen_t len;
				struct sockaddr_in peer;
				len = sizeof peer;
				getpeername(mySocket, (struct sockaddr*)&peer, &len);
				pthread_mutex_lock(&PrintLock);
		//		cout<<"Received STRQ from "<<ntohs(peer.sin_port)<<endl;
				for (int ite=0;ite<20;ite++)
				{
					//printf("%02x",(unsigned char)h1.UOID[ite]);
				}
				pthread_mutex_unlock(&PrintLock);
				Flood_Elem *fd_obj = new Flood_Elem();
				list<Flood_Elem*>* locEventQ = new list<Flood_Elem*>;
				fd_obj->UOID = new unsigned char[20];
				fd_obj->respUOID = new unsigned char[20];
				fd_obj->MessageType = h1.MessageType;
				if(i1->TTL==0){fd_obj->TTL=(unsigned char)30;}else{fd_obj->TTL=(unsigned char)i1->TTL;}
				fd_obj->TTL = (unsigned char)min((int)fd_obj->TTL,((int)(h1.TTL)-1));
				memcpy(fd_obj->UOID,h1.UOID,20);
				pthread_mutex_lock(&DBaseLock);
				DBase->Append((void *)(fd_obj->UOID));
				pthread_mutex_unlock(&DBaseLock);
				memcpy(&statustype,&readBuf[27],1);
				if (statustype==files)
				{
					fd_obj->Distance = 8;
					//---------------------------------------------- RESET----------------------------------------------------//
					pthread_mutex_lock(&log_lock);
					FILE *Log = fopen(LogLocation.c_str(),"a");
					if(Log==NULL)
					{
					cerr<<"Log file can not be opened. The program will continue without logging."<<endl;
					}else{
					gettimeofday(&tim,NULL);
					fprintf(Log,"f %10ld.%03d nunki.usc.edu_%d STRQ %d ",(tim.tv_sec),(int)((tim.tv_usec)/1000),ntohs(peer.sin_port),(int)(h1.TTL));
					for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(h1.UOID)[pr]);}
					fprintf(Log," neighbors\n");
					fflush(Log);
					}
					fclose(Log);
					pthread_mutex_unlock(&log_lock);
					//---------------------------------------------------------------------------------------------------------//

				}
				else if (statustype == neighbors)
				{
					fd_obj->Distance = 2;
				}

				Catch =1;
				pthread_mutex_lock(&DBaseLock);
				Catch = eval_DBase();
				pthread_mutex_unlock(&DBaseLock);
			//	cout<<"ReadCatch "<<Catch<<endl;

				if (Catch == 1)
				{
					*locEventQ = Gelem->ListP;
					list<GlobalList_Elem*>::iterator it;
					pthread_mutex_lock(&GlobalList_lock);
					for (it =GlobalList.begin();it!=GlobalList.end();it++ )
					{
						GlobalList_Elem *g1 = NULL;
						g1 = (GlobalList_Elem*) (*it);
						if ((*it)!=NULL)
						{
							if (g1->Temp!=1 && g1->Temp!=2)
							{
							pthread_mutex_lock(&PrintLock);
						//	cout<<"Flooding STRQ to "<<g1->Port<<endl;
							pthread_mutex_unlock(&PrintLock);
							pthread_mutex_lock(&g1->EventQlock);
							(g1->ListP).push_back(fd_obj);
							pthread_mutex_unlock(&g1->EventQlock);
							pthread_cond_broadcast(&g1->EventQ_cv);
							}
						}

					}
					pthread_mutex_unlock(&GlobalList_lock);
					int memMap = 100;
					Flood_Elem *fd_obj1 = new Flood_Elem();
					fd_obj1->UOID = new unsigned char[20];
					fd_obj1->respUOID = new unsigned char[20];

					if(i1->TTL==0){fd_obj1->TTL=(unsigned char)30;}else{fd_obj1->TTL=(unsigned char)i1->TTL;}
					fd_obj1->TTL = (unsigned char)min((int)fd_obj1->TTL,((int)(h1.TTL)-1));
					fd_obj1->MessageType = STRS;
					fd_obj1->respPort = i1->Port;
					memcpy(fd_obj1->respUOID,(GetUOID(node_instance_id,"msg")),20);
					memcpy(fd_obj1->UOID,h1.UOID,20);
					fd_obj1->Distance=fd_obj->Distance;
					memMap = memcmp(fd_obj1->respUOID,fd_obj1->UOID,20);
					if (memMap!=0)
					{
					//	cout<<"Sending STRS back to "<<ntohs(peer.sin_port)<<endl;
						pthread_mutex_lock(&Gelem->EventQlock);
						(Gelem->ListP).push_back(fd_obj1);
						pthread_cond_signal(&Gelem->EventQ_cv);		
						pthread_mutex_unlock(&Gelem->EventQlock);
					}else;
				}//END IF CATCH

//			   }// END IF neighbors


		}//END IF STRQ
		//-------------------------------------------------------- END STRQ READ -----------------------------------------//
		
		if(h1.MessageType == JNRQ)
		{
			struct JOIN_MSG msg1;
			memset(&msg1,0,sizeof msg1);
			msg1.HostName = new char[13];
			for (unsigned int it3 = 27;it3<27+h1.DataLength;it3++ )
			{
				if ((numBytes = read(mySocket,&readBuf[it3], 1))==-1)
				{
			//		perror("read");
				}
			}			
			memcpy(&msg1.HostLocation,&readBuf[27],4);
			memcpy(&msg1.HostPort,&readBuf[31],2);
			memcpy(msg1.HostName,&readBuf[33],13);

            
            //---------------------------------------------- RESET----------------------------------------------------//
			pthread_mutex_lock(&log_lock);
			FILE *Log = fopen(LogLocation.c_str(),"a");
			if(Log==NULL)
			{
			cerr<<"Log file can not be opened. The program will continue without logging."<<endl;
			}else{
			gettimeofday(&tim,NULL);
			fprintf(Log,"r %10ld.%03d nunki.usc.edu_%d JNRQ %d ",(tim.tv_sec),(int)((tim.tv_usec)/1000),msg1.HostPort,(int)(h1.TTL));
			for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(h1.UOID)[pr]);}
			fprintf(Log," %d nunki.usc.edu\n",msg1.HostPort);
			fflush(Log);
			}
			fclose(Log);
			pthread_mutex_unlock(&log_lock);
			//---------------------------------------------------------------------------------------------------------//

			Flood_Elem *fd_obj = new Flood_Elem();
			list<Flood_Elem*>* locEventQ = new list<Flood_Elem*>;
			fd_obj->UOID = new unsigned char[20];
			fd_obj->respUOID = new unsigned char[20];
			fd_obj->MessageType = h1.MessageType;
			fd_obj->Port = msg1.HostPort;
			fd_obj->HostLocation = msg1.HostLocation;
			fd_obj->TTL = h1.TTL;
			fd_obj->TTL = (unsigned char)(((int)fd_obj->TTL)- 1);
			memcpy(fd_obj->UOID,h1.UOID,20);
			pthread_mutex_lock(&DBaseLock);
			DBase->Append((void *)(fd_obj->UOID));
			pthread_mutex_unlock(&DBaseLock);

/*			//-------------------------TESTING-------------------------------------BEGIN//
			pthread_mutex_lock(&PrintLock);
			cout<<"JNRQ in the read thread"<<endl; 
			cout<<"Port inside read "<<fd_obj->Port<<endl;
			cout<<"TTL inside read "<<(int)fd_obj->TTL<<endl;
			cout<<"Host Location read write "<<fd_obj->HostLocation<<endl;
			cout<<"UOID inside read ";
			for(int it2=0;it2<20;it2++){
							printf("%02x",(unsigned char)(fd_obj->UOID)[it2]);
					}cout<<endl;
			pthread_mutex_unlock(&PrintLock);
			//-------------------------TESTING-------------------------------------END//
*/            
			Catch = eval_DBase();
			if (Catch == 1)
			{
				*locEventQ = Gelem->ListP;
				list<GlobalList_Elem*>::iterator it;
				pthread_mutex_lock(&GlobalList_lock);
				for (it =GlobalList.begin();it!=GlobalList.end();it++ )
				{
					GlobalList_Elem *g1 = NULL;
					g1 = (GlobalList_Elem*) (*it);
					if ((*it)!=NULL)
					{
						if (g1->Temp!=1 && g1->Temp!=2)
						{
						
						pthread_mutex_lock(&PrintLock);
						pthread_mutex_unlock(&PrintLock);
						pthread_mutex_lock(&g1->EventQlock);
						(g1->ListP).push_back(fd_obj);
						pthread_mutex_unlock(&g1->EventQlock);
						pthread_cond_broadcast(&g1->EventQ_cv);
						}
					}

				}
				pthread_mutex_unlock(&GlobalList_lock);
				Flood_Elem *fd_obj1 = new Flood_Elem();
				fd_obj1->UOID = new unsigned char[20];
				fd_obj1->respUOID = new unsigned char[20];
				fd_obj1->MessageType = JNRS;
				fd_obj1->Port = msg1.HostPort;
				fd_obj1->respPort = i1->Port;
				memcpy(fd_obj1->respUOID,(GetUOID(node_instance_id,"msg")),20);
				memcpy(fd_obj1->UOID,h1.UOID,20);
				
				fd_obj1->HostLocation = i1->Location;
				fd_obj1->Distance = (unsigned int)abs((int)(i1->Location) - (int)(fd_obj->HostLocation));
				
				if(i1->TTL==0){fd_obj1->TTL=(unsigned char)30;}else{fd_obj1->TTL=(unsigned char)i1->TTL;}
				fd_obj1->TTL = (unsigned char)min((int)fd_obj1->TTL,((int)(h1.TTL)-1));

				
				pthread_mutex_lock(&Gelem->EventQlock);
				*locEventQ = Gelem->ListP;
				(Gelem->ListP).push_back(fd_obj1);
				pthread_cond_signal(&Gelem->EventQ_cv);

				pthread_mutex_unlock(&Gelem->EventQlock);

				//delete fd_obj1;
	
			}//end IF CATCH == 1
		}//END IF MSG TYPE = JNRQ 

		
		if (h1.MessageType == JNRS)
		{
			struct JOIN_RES respMsg1;
			memset(&respMsg1,0,sizeof respMsg1);
			respMsg1.UOID = new unsigned char[20];
			respMsg1.HostName = new char[13];
			unsigned int it9 = 0;
			for (unsigned int it3 = 27;it3<27+39;it3++ )
			{
				if ((numBytes = read(mySocket,&readBuf[it3], 1))==-1)
				{
			//		perror("read");
					
				}
				it9 = it3;
			}
			memcpy(respMsg1.UOID,&readBuf[27],20);
			memcpy(&respMsg1.Distance,&readBuf[47],4);
			memcpy(&respMsg1.HostPort,&readBuf[51],2);
			memcpy(&respMsg1.HostName,&readBuf[53],13);


			//---------------------------------------------- RESET----------------------------------------------------//
			pthread_mutex_lock(&log_lock);
			FILE *Log = fopen(LogLocation.c_str(),"a");
			if(Log==NULL)
			{
			cerr<<"Log file can not be opened. The program will continue without logging."<<endl;
			}else{
			gettimeofday(&tim,NULL);
			fprintf(Log,"r %10ld.%03d nunki.usc.edu_%d JNRS %d ",(tim.tv_sec),(int)((tim.tv_usec)/1000),respMsg1.HostPort,(int)(h1.TTL));
			for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(h1.UOID)[pr]);}
			fprintf(Log," ");
			for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(respMsg1.UOID)[pr]);}
			fprintf(Log," %d %d nunki.usc.edu\n",respMsg1.Distance,respMsg1.HostPort);
			fflush(Log);
			}
			fclose(Log);
			pthread_mutex_unlock(&log_lock);
			//---------------------------------------------------------------------------------------------------------//


			Flood_Elem *fd_obj1 = new Flood_Elem();
	
			fd_obj1->UOID = new unsigned char[20];
			fd_obj1->respUOID = new unsigned char[20];
			int memMap = 100;
			list<GlobalList_Elem*>::iterator it;

			for (it =GlobalList.begin();it!=GlobalList.end();it++ )
			{
				if ((*it)->Temp!=2)
				{
				
				memMap = memcmp(respMsg1.UOID,((*it)->UOID),20);
				if (memMap == 0)
				{
					fd_obj1->MessageType = h1.MessageType;
					fd_obj1->Port = (*it)->Port;
					fd_obj1->respPort = respMsg1.HostPort;
					for (int iter = 0;iter<20;iter++)
					{
						fd_obj1->respUOID[iter] = h1.UOID[iter];
						fd_obj1->UOID[iter] = respMsg1.UOID[iter];
					}
					fd_obj1->HostLocation = i1->Location;
					fd_obj1->Distance = respMsg1.Distance;
					if(i1->TTL==0){fd_obj1->TTL=(unsigned char)30;}else{fd_obj1->TTL=(unsigned char)i1->TTL;}
					fd_obj1->TTL = (unsigned char)min((int)fd_obj1->TTL,((int)(h1.TTL)-1));
					if (fd_obj1->MessageType == JNRS)
					{
						pthread_mutex_lock(&(*it)->EventQlock);
						((*it)->ListP).push_back(fd_obj1);
						pthread_cond_signal(&((*it)->EventQ_cv));
						pthread_mutex_unlock(&((*it)->EventQlock));
						pthread_mutex_unlock(&GlobalList_lock);

					}
					
				}else;
				}
			}//end for loop
			
		}//end else jnrs
		
	}//end while

	
	pthread_exit(NULL);
}
//----------------------------------------- READ THREAD TO BE END -------------------------------------------------//


//----------------------------------------- WRITE THREAD BEGIN -----------------------------------------------------//

void *writethread(void *threadarg)
{
		//cout<<"***********************************************"<<endl;
	int mySocket;
	GlobalList_Elem* Gelem = (GlobalList_Elem *)threadarg;
	mySocket = Gelem->Socket;
	socklen_t len;
	struct sockaddr_in peer;
	len = sizeof peer;
	getpeername(mySocket, (struct sockaddr*)&peer, &len);
	
	while(1){
	Flood_Elem *fd_obj = new Flood_Elem();
	list<Flood_Elem*>* locEventQ = new list<Flood_Elem*>;
	fd_obj->UOID = new unsigned char[20];
	fd_obj->respUOID = new unsigned char[20];
	fd_obj->FileName = new char[25];
	fd_obj->Sha1 = new char[40];
	fd_obj->Nonce = new char[40];

	pthread_mutex_lock(&Gelem->EventQlock);
	if ((Gelem->ListP).size()==0)
	{
		pthread_cond_wait(&Gelem->EventQ_cv,&Gelem->EventQlock);
	}
	pthread_mutex_unlock(&Gelem->EventQlock);
	pthread_mutex_lock(&DBaseLock);	
	*locEventQ = Gelem->ListP;
	fd_obj = (Flood_Elem*)((*locEventQ).front());
	DBase->Append((void *)(fd_obj->UOID));
	pthread_mutex_unlock(&DBaseLock);
	pthread_mutex_lock(&Gelem->EventQlock);	
	(Gelem->ListP).pop_front();
	pthread_mutex_unlock(&Gelem->EventQlock);

	if (fd_obj->MessageType==SHRS)
	{
		unsigned char *searchResp1 = new unsigned char[512];
		memset(searchResp1,0,512);
		struct HEADER sHeader;
		memset(&sHeader,0,sizeof sHeader);
		struct SRCH_RES srchRes;
		memset(&srchRes,0,sizeof srchRes);
		
		sHeader.MessageType = SHRS;
        sHeader.UOID = new unsigned char[20];
		for(int it2=0;it2<20;it2++){
					sHeader.UOID[it2]=fd_obj->respUOID[it2];
				}
		
		sHeader.TTL = (unsigned char)(fd_obj->TTL);
		sHeader.Reserved = (unsigned char)0;

		srchRes.UOID = new unsigned char[20];
		memcpy(srchRes.UOID,fd_obj->UOID,20);
		char srbuf[50];
		int indexFileLocal = fd_obj->password;
		sprintf(srbuf,"%d",indexFileLocal);
	//	string NodeHome = (string(HomeDir1)).substr(0,(int)strlen(HomeDir1)-1);
	//	string FilesHome = NodeHome + "/files";
		string FileN1 = FilesHome +"/"+string(srbuf) +".meta";
		struct stat st;
		stat(FileN1.c_str(),&st);
		srchRes.NextLength = st.st_size;
		sHeader.DataLength = 20+4+20+srchRes.NextLength;
		memcpy(&searchResp1[0],&sHeader.MessageType,1);
		memcpy(&searchResp1[1],sHeader.UOID,20);
		memcpy(&searchResp1[21],&sHeader.TTL,1);
		memcpy(&searchResp1[22],&sHeader.Reserved,1);
		memcpy(&searchResp1[23],&sHeader.DataLength,4);
		memcpy(&searchResp1[27],fd_obj->UOID,20);
		memcpy(&searchResp1[47],&srchRes.NextLength,4);
		My570ListElem * kurr = new My570ListElem();
		for(kurr=fileidList->First();kurr!=NULL;kurr=fileidList->Next(kurr))
		{
			if(((Boot_Elem*)(kurr->Obj()))->index == indexFileLocal)
			{
				memcpy(&searchResp1[51],((Boot_Elem*)(kurr->Obj()))->FileId,20);
				break;
			}
		}
		for (int it = 0;it<70 ;it++)
		{
			if (write(mySocket,&searchResp1[it],1)==-1)
				{
					//perror("beaconconnect: write");
	//				cout<<"CheckWrite1:"<<errno<<endl; 
			//		exit(1);
				}

		}		
		FILE *pf2 = fopen(((string(FileN1)).c_str()),"r");
		

		unsigned int filecount = (unsigned int)(FileSizePrint)/8192;
		unsigned int actsize1 = FileSizePrint;

		if (filecount>=1 && (FileSizePrint%8192)!=0){
			filecount=filecount+1;
		}else{
			if (filecount==0)
			{
				filecount=1;
			}else{
				filecount=FileSizePrint/8192;
			}
		}
		   unsigned int buf_count1 =0;
		   for(unsigned int icount=0;icount<filecount;icount++){

			   if(actsize1>=8192){
				   buf_count1=8192;
			   }else{
				   buf_count1=actsize1;
			   }
			   actsize1 = actsize1 - 8192;
			unsigned char* MsgBuf1 = (unsigned char*)malloc(8192);
		   memset(MsgBuf1,0,8192);
			size_t bytes_read1;
		   bytes_read1 = fread(MsgBuf1,1,buf_count1,pf2);
		   	for (unsigned int it = 0;it<bytes_read1 ;it++)
			{
				if (write(mySocket,&MsgBuf1[it],1)==-1)
					{
						//perror("beaconconnect: write");
		//				cout<<"CheckWrite1:"<<errno<<endl; 
				//		exit(1);
					}

			}

       buf_count1=0;
	   free(MsgBuf1);
	   }//count for loop
	   fclose(pf2);
	   //---------------sending actual file--------------END------------//			

	}
	if (fd_obj->MessageType==SHRQ)
	{
		unsigned char *searchMsg1 = new unsigned char[512];
		struct HEADER sHeader;
		memset(&sHeader,0,sizeof sHeader);
		struct SRCH_MSG srchMsg;
		memset(&srchMsg,0,sizeof srchMsg);
		
		sHeader.MessageType = SHRQ;
        sHeader.UOID = new unsigned char[20];
		for(int it2=0;it2<20;it2++){
					sHeader.UOID[it2]=fd_obj->UOID[it2];
				}
		
		sHeader.TTL = (unsigned char)(fd_obj->TTL);
		sHeader.Reserved = (unsigned char)0;
		if (fd_obj->Distance==1)
		{
			srchMsg.SearchType=srchFileName;
			sHeader.DataLength = string(fd_obj->FileName).length()+1;
			strcpy(srchMsg.Query,string(fd_obj->FileName).c_str());
		}
		if (fd_obj->Distance==2)
		{
			srchMsg.SearchType=srchSha1;
			sHeader.DataLength = string(fd_obj->Sha1).length()+1;
			strcpy(srchMsg.Query,string(fd_obj->Sha1).c_str());
		}
		if (fd_obj->Distance==3)
		{
			srchMsg.SearchType=srchKeys;
			sHeader.DataLength = string(fd_obj->Nonce).length()+1;
			strcpy(srchMsg.Query,string(fd_obj->Nonce).c_str());
		}
		memcpy(&searchMsg1[0],&sHeader.MessageType,1);
		memcpy(&searchMsg1[1],sHeader.UOID,20);
		memcpy(&searchMsg1[21],&sHeader.TTL,1);
		memcpy(&searchMsg1[22],&sHeader.Reserved,1);
		memcpy(&searchMsg1[23],&sHeader.DataLength,4);
		memcpy(&searchMsg1[27],&srchMsg.SearchType,1);
		memcpy(&searchMsg1[28],srchMsg.Query,string(srchMsg.Query).length());
		for (int it = 0;it<27;it++)
		{
			if (write(mySocket,&searchMsg1[it],1)==-1)
				{
					//perror("beaconconnect: write");
	//				cout<<"CheckWrite1:"<<errno<<endl; 
			//		exit(1);
				}

		}	
		for (unsigned int i=27;i<27+sHeader.DataLength;i++)
		{
			if (write(mySocket,&searchMsg1[i],1)==-1)
			{
				//perror("beaconconnect: write");
				//cout<<"CheckWrite1:"<<errno<<endl; 
			//		exit(1);
			}
		}
	
	}

	if (fd_obj->MessageType==DELT)
	{
		unsigned char *delMsg = new unsigned char[512];
		struct HEADER sHeader;
		memset(&sHeader,0,sizeof sHeader);
		//unsigned short HostPort = i1->Port;
		sHeader.MessageType = DELT;
        sHeader.UOID = new unsigned char[20];
		for(int it2=0;it2<20;it2++){
					sHeader.UOID[it2]=fd_obj->UOID[it2];
				}
		
		sHeader.TTL = (unsigned char)(fd_obj->TTL);
		sHeader.Reserved = (unsigned char)0;
		sHeader.DataLength = ((string(fd_obj->FileName)).length())+ ((string(fd_obj->Sha1)).length()) + ((string(fd_obj->Nonce)).length()) + 4;
		memcpy(&delMsg[0],&sHeader.MessageType,1);
		memcpy(&delMsg[1],sHeader.UOID,20);
		memcpy(&delMsg[21],&sHeader.TTL,1);
		memcpy(&delMsg[22],&sHeader.Reserved,1);
		memcpy(&delMsg[23],&sHeader.DataLength,4);
		for (int it = 0;it<27;it++)
		{
			if (write(mySocket,&delMsg[it],1)==-1)
				{
					//perror("beaconconnect: write");
	//				cout<<"CheckWrite1:"<<errno<<endl; 
			//		exit(1);
				}

		}
		memcpy(&delMsg[27],fd_obj->FileName,(string(fd_obj->FileName)).length());
		memcpy(&delMsg[27+(string(fd_obj->FileName)).length()],fd_obj->Sha1,((string(fd_obj->Sha1)).length()));
		memcpy(&delMsg[27+(string(fd_obj->FileName)).length()+((string(fd_obj->Sha1)).length())],fd_obj->Nonce,((string(fd_obj->Nonce)).length()));
		memcpy(&delMsg[27+(string(fd_obj->FileName)).length()+((string(fd_obj->Sha1)).length())+((string(fd_obj->Nonce)).length())],&fd_obj->password,4);
/*		pthread_mutex_lock(&PrintLock);
		for (int i=27+(string(fd_obj->FileName)).length()+((string(fd_obj->Sha1)).length());i<27+(string(fd_obj->FileName)).length()+((string(fd_obj->Sha1)).length())+((string(fd_obj->Nonce)).length());i++)
		{
			cout<<delMsg[i];
		}cout<<endl;
		cout<<(string(fd_obj->Sha1)).length();//<<" "<<27+(string(fd_obj->FileName)).length()+84<<endl;
		pthread_mutex_unlock(&PrintLock);
*/	
		for (unsigned int i=27;i<27+sHeader.DataLength;i++)
		{
			if (write(mySocket,&delMsg[i],1)==-1)
			{
				//perror("beaconconnect: write");
				//cout<<"CheckWrite1:"<<errno<<endl; 
			//		exit(1);
			}
		}
			pthread_mutex_lock(&log_lock);
			FILE *Log = fopen(LogLocation.c_str(),"a");
			if(Log==NULL)
			{
			cerr<<"Log file can not be opened. The program will continue without logging."<<endl;
			}else{
			gettimeofday(&tim,NULL);
			fprintf(Log,"s %10ld.%03d nunki.usc.edu_%d DELT %d ",(tim.tv_sec),(int)((tim.tv_usec)/1000),ntohs(peer.sin_port),(int)(fd_obj->TTL));
			for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(fd_obj->UOID)[pr]);}
			fprintf(Log,"\n");
			fflush(Log);
			}
			fclose(Log);
			pthread_mutex_unlock(&log_lock);

	}
	if (fd_obj->MessageType==STOR)
	{
	
		unsigned char *storeMsg = new unsigned char[512];
		struct HEADER sHeader;
		memset(&sHeader,0,sizeof sHeader);
		sHeader.MessageType = STOR;
        sHeader.UOID = new unsigned char[20];
		for(int it2=0;it2<20;it2++){
					sHeader.UOID[it2]=fd_obj->UOID[it2];
				}
		
		sHeader.TTL = (unsigned char)(fd_obj->TTL);
		sHeader.Reserved = (unsigned char)0;

		sHeader.DataLength = 4+St_Elem->MetaSize+FileSizePrint;
		memcpy(&storeMsg[0],&sHeader.MessageType,1);
		memcpy(&storeMsg[1],sHeader.UOID,20);
		memcpy(&storeMsg[21],&sHeader.TTL,1);
		memcpy(&storeMsg[22],&sHeader.Reserved,1);
		memcpy(&storeMsg[23],&sHeader.DataLength,4);
		memcpy(&storeMsg[27],&St_Elem->MetaSize,4);
		
		pthread_mutex_lock(&PrintLock);
		pthread_mutex_unlock(&PrintLock);		
		//cout<<"Sending STOR request"<<endl;
	   //---------------sending Header--------------BEGIN------------//
		for (int it = 0;it<31 ;it++)
		{
			if (write(mySocket,&storeMsg[it],1)==-1)
				{
					//perror("beaconconnect: write");
	//				cout<<"CheckWrite1:"<<errno<<endl; 
			//		exit(1);
				}

		}
	   //---------------sending Header--------------END------------//
	   //---------------sending Metafile--------------BEGIN------------//
		FILE *pf1 = fopen(((string(St_Elem->MetaName)).c_str()),"r");
		unsigned int metacount = (unsigned int)(St_Elem->MetaSize)/8192;
		unsigned int actsize = St_Elem->MetaSize;
	
		if (metacount>=1 && (St_Elem->MetaSize%8192)!=0){
			metacount=metacount+1;
		}else{
			if (metacount==0)
			{
				metacount=1;
			}else{
				metacount=St_Elem->MetaSize/8192;
			}
		}
		   unsigned int buf_count =0;
		   for(unsigned int icount=0;icount<metacount;icount++){

			   if(actsize>=8192){
				   buf_count=8192;
			   }else{
				   buf_count=actsize;
			   }
			   actsize = actsize - 8192;
			unsigned char* MsgBuf = (unsigned char*)malloc(8192);
		   memset(MsgBuf,0,8192);
			size_t bytes_read;
		   bytes_read= fread(MsgBuf,1,buf_count,pf1);
			for (unsigned int it = 0;it<bytes_read ;it++)
			{
				if (write(mySocket,&MsgBuf[it],1)==-1)
					{
						//perror("beaconconnect: write");
		//				cout<<"CheckWrite1:"<<errno<<endl; 
				//		exit(1);
					}

			}
       buf_count=0;
	   free(MsgBuf);
	   }//count for loop
	   fclose(pf1);
//	   cout<<"STOR sent"<<endl;
	   //---------------sending Metafile--------------END------------//

	   //---------------sending actual file--------------BEGIN------------//
		FILE *pf2 = fopen(((string(St_Elem->FileName)).c_str()),"r");
		

		unsigned int filecount = (unsigned int)(FileSizePrint)/8192;
		unsigned int actsize1 = FileSizePrint;

		if (filecount>=1 && (FileSizePrint%8192)!=0){
			filecount=filecount+1;
		}else{
			if (filecount==0)
			{
				filecount=1;
			}else{
				filecount=FileSizePrint/8192;
			}
		}
		   unsigned int buf_count1 =0;
		   for(unsigned int icount=0;icount<filecount;icount++){

			   if(actsize1>=8192){
				   buf_count1=8192;
			   }else{
				   buf_count1=actsize1;
			   }
			   actsize1 = actsize1 - 8192;
			unsigned char* MsgBuf1 = (unsigned char*)malloc(8192);
		   memset(MsgBuf1,0,8192);
			size_t bytes_read1;
		   bytes_read1 = fread(MsgBuf1,1,buf_count1,pf2);
		   	for (unsigned int it = 0;it<bytes_read1 ;it++)
			{
				if (write(mySocket,&MsgBuf1[it],1)==-1)
					{
						//perror("beaconconnect: write");
		//				cout<<"CheckWrite1:"<<errno<<endl; 
				//		exit(1);
					}

			}

       buf_count1=0;
	   free(MsgBuf1);
	   }//count for loop
	   fclose(pf2);
	   //---------------sending actual file--------------END------------//			

	//	memcpy(&storeMsg[31],St_Elem->)
		//struct STOR_MSG stMsg;
		//memset(&stMsg,0,sizeof stMsg);
		//stMsg.MetaLength = St_Elem->MetaSize;
		//memcpy
			pthread_mutex_lock(&log_lock);
			FILE *Log = fopen(LogLocation.c_str(),"a");
			if(Log==NULL)
			{
			cerr<<"Log file can not be opened. The program will continue without logging."<<endl;
			}else{
			gettimeofday(&tim,NULL);
			fprintf(Log,"s %10ld.%03d nunki.usc.edu_%d STOR %d ",(tim.tv_sec),(int)((tim.tv_usec)/1000),ntohs(peer.sin_port),(int)(fd_obj->TTL));
			for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(fd_obj->UOID)[pr]);}
			fprintf(Log,"\n");
			fflush(Log);
			}
			fclose(Log);
			pthread_mutex_unlock(&log_lock);


	}
	if (fd_obj->MessageType==NTFY)
	{
			unsigned char *writeBuf = new unsigned char[512];
			unsigned char Reserved = (unsigned char)0;
			int DataLength = 1;
			struct JOIN_MSG msg;
			memset(&msg,0,sizeof msg);
				msg.HostPort=i1->Port;
			memcpy(&writeBuf[0],&(fd_obj->MessageType),1);
			memcpy(&writeBuf[1],fd_obj->UOID,20);
			memcpy(&writeBuf[21],&(fd_obj->TTL),1);
			memcpy(&writeBuf[22],&Reserved,1);
			memcpy(&writeBuf[23],&DataLength,4);
			memcpy(&writeBuf[27],&msg.HostPort,2);
			
		//	cout<<"jlksdajflkjalskfdj "<<msg.HostPort<<endl;
			for (int it = 0;it<29 ;it++)
			{
				if (write(mySocket,&writeBuf[it],1)==-1)
					{
						//perror("beaconconnect: write");
		//				cout<<"CheckWrite1:"<<errno<<endl; 
				//		exit(1);
					}

			}

/*			for (int it=27;it<29;it++)
			{
				if (write(mySocket,&writeBuf[it],1)==-1)
				{
			
						cout<<"CheckWrite1:"<<errno<<endl;
				}
			}
*/			pthread_mutex_lock(&log_lock);
			FILE *Log = fopen(LogLocation.c_str(),"a");
			if(Log==NULL)
			{
			cerr<<"Log file can not be opened. The program will continue without logging."<<endl;
			}else{
			gettimeofday(&tim,NULL);
			fprintf(Log,"s %10ld.%03d nunki.usc.edu_%d NTFY %d ",(tim.tv_sec),(int)((tim.tv_usec)/1000),ntohs(peer.sin_port),(int)(fd_obj->TTL));
			for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(fd_obj->UOID)[pr]);}
			fprintf(Log," ");
			fprintf(Log,"shutdown\n");
			fflush(Log);
			}
			fclose(Log);
			pthread_mutex_unlock(&log_lock);

	//		cout<<"Sent NTFY"<<endl;		
		
	}
	if (fd_obj->MessageType==KPAV){
			
			unsigned char *writeBuf = new unsigned char[512];
			unsigned char Reserved = (unsigned char)0;
			unsigned int DataLength = 0;
			memcpy(&writeBuf[0],&(fd_obj->MessageType),1);
			memcpy(&writeBuf[1],fd_obj->UOID,20);
			memcpy(&writeBuf[21],&(fd_obj->TTL),1);
			memcpy(&writeBuf[22],&Reserved,1);
			memcpy(&writeBuf[23],&DataLength,4);			
			for (int it = 0;it<27 ;it++ )
			{
				if (write(mySocket,&writeBuf[it],1)==-1)
					{
				//		perror("beaconconnect: write");///call send_check function
	//					cout<<"CheckWrite2:"<<errno<<endl;
//						exit(1);
					}
			}	
			pthread_mutex_lock(&log_lock);
			FILE *Log = fopen(LogLocation.c_str(),"a");
			if(Log==NULL)
			{
			cerr<<"Log file can not be opened. The program will continue without logging."<<endl;
			}else{
			gettimeofday(&tim,NULL);
			fprintf(Log,"s %10ld.%03d nunki.usc.edu_%d KPAV %d ",(tim.tv_sec),(int)((tim.tv_usec)/1000),ntohs(peer.sin_port),(int)(fd_obj->TTL));
			for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(fd_obj->UOID)[pr]);}
			fprintf(Log,"\n");
			fflush(Log);
			}
			fclose(Log);
			pthread_mutex_unlock(&log_lock);
	//		cout<<"Sent KPAV"<<endl;
		
	}
	//------------------------------------------------------------------------------STRS -----------------------------BEGIN-------//

	if(fd_obj->MessageType==STRS)
	{
	    struct HEADER sHeader;
		short HostInfoLength = 15;
		int RecordLength = 15;
		int RecordZero = 0;
		unsigned short HostPort = i1->Port;

		sHeader.MessageType = STRS;
        sHeader.UOID = new unsigned char[20];
		for(int it2=0;it2<20;it2++){
					sHeader.UOID[it2]=fd_obj->respUOID[it2];
				}
		
		sHeader.TTL = (unsigned char)(fd_obj->TTL);
		sHeader.Reserved = (unsigned char)0;
		sHeader.DataLength = 20+2+2+13;
		unsigned char* StatusMsg = new unsigned char[512];
		memcpy(&StatusMsg[0],&sHeader.MessageType,1);
		memcpy(&StatusMsg[1],sHeader.UOID,20);
		memcpy(&StatusMsg[21],&sHeader.TTL,1);
		memcpy(&StatusMsg[22],&sHeader.Reserved,1);
		if (fd_obj->Distance==2)
		{
			sHeader.DataLength =  sHeader.DataLength+(19*(GlobalList.size()))+1;
			memcpy(&StatusMsg[23],&sHeader.DataLength,4);
			memcpy(&StatusMsg[27],fd_obj->UOID,20);
			memcpy(&StatusMsg[47],&HostInfoLength,2);
			memcpy(&StatusMsg[49],&HostPort,2);
			memcpy(&StatusMsg[51],&hostname,13);
		
		   //iterate here for record length and data
		   int RecordIter=64;
		   list<GlobalList_Elem*>::iterator it;
		   pthread_mutex_lock(&GlobalList_lock);

		   for (it =GlobalList.begin();it!=GlobalList.end();it++ )
		   {
				   GlobalList_Elem *g1 = NULL;
				   g1 = (GlobalList_Elem*) (*it);
				   if ((*it)!=NULL)
				   {
						  // i=64+i;
	//					  cout<<"Neighbor Port: "<<(*it)->Port<<endl;
						   memcpy(&StatusMsg[RecordIter],&RecordLength,4);
						   memcpy(&StatusMsg[RecordIter+4],&((*it)->Port),2);
						   memcpy(&StatusMsg[RecordIter+6],&hostname,13);
						   RecordIter=RecordIter+19;
				   }

		   }
		   pthread_mutex_unlock(&GlobalList_lock);
		   memcpy(&StatusMsg[RecordIter],&RecordZero,4);

			   ////	
			   //----------------------------------------- SENDING MESSAGE ------------------------------------- BEGIN--//
			   for (unsigned int it = 0;it<27 ;it++ )
				{
						if (write(mySocket,&StatusMsg[it],1)==-1)
							{
							//	perror("beaconconnect: write");
								exit(1);
							}
				}

				for (unsigned int it5 = 27;it5<27+sHeader.DataLength; it5++ )
				{
						if (write(mySocket,&StatusMsg[it5],1)==-1)
						{
						//	perror("beaconconnect: write");
							exit(1);
						}	
				}

						//---------------------------------------------- RESET----------------------------------------------------//
				pthread_mutex_lock(&log_lock);
				FILE *Log = fopen(LogLocation.c_str(),"a");
				if(Log==NULL)
				{
				cerr<<"Log file can not be opened. The program will continue without logging."<<endl;
				}else{
				gettimeofday(&tim,NULL);
				fprintf(Log,"s %10ld.%03d nunki.usc.edu_%d STRS %d ",(tim.tv_sec),(int)((tim.tv_usec)/1000),ntohs(peer.sin_port),(int)(sHeader.TTL));
				for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(sHeader.UOID)[pr]);}
				fprintf(Log," ");
				for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(fd_obj->respUOID)[pr]);}
				fprintf(Log,"\n");
				fflush(Log);
				}
				fclose(Log);
				pthread_mutex_unlock(&log_lock);
			   //----------------------------------------- SENDING MESSAGE ------------------------------------- END---//

		}
		else if(fd_obj->Distance==8){
			sHeader.DataLength = sHeader.DataLength+4;
			if (nameList->Length()==0)
			{
				memcpy(&StatusMsg[23],&sHeader.DataLength,4);
				   //----------------------------------------- SENDING MESSAGE ------------------------------------- BEGIN--//
				   for (unsigned int it = 0;it<27 ;it++ )
					{
							if (write(mySocket,&StatusMsg[it],1)==-1)
								{
								//	perror("beaconconnect: write");
									exit(1);
								}
					}
				memcpy(&StatusMsg[27],fd_obj->respUOID,20);
				memcpy(&StatusMsg[47],&HostInfoLength,2);
				memcpy(&StatusMsg[49],&HostPort,2);
				memcpy(&StatusMsg[51],&hostname,13);
				int RLzero=0;
				memcpy(&StatusMsg[64],&RLzero,4);
				   for (unsigned int it = 27;it<64 ;it++ )
					{
							if (write(mySocket,&StatusMsg[it],1)==-1)
								{
								//	perror("beaconconnect: write");
								//	exit(1);
								}
					}
					for (unsigned int it=64;it<68;it++)
					{
								if (write(mySocket,&StatusMsg[it],1)==-1)
								{
								//	perror("beaconconnect: write");
								//	exit(1);
								}					}
			}
			if(nameList->Length()!=0)
			{
				struct stat st;
				My570ListElem* elem = new My570ListElem();
				for(elem=nameList->First();elem!=NULL;elem=nameList->Next(elem))
				{

					string NodeHome = (string(HomeDir1)).substr(0,(int)strlen(HomeDir1)-1);
					string FilesHome = NodeHome + "/files";
					int LocalIndex=((Boot_Elem*)(elem->Obj()))->index; 
					char myCurrName[100];
					sprintf(myCurrName,"%d",LocalIndex);
					string MetaName = FilesHome +"/"+string(myCurrName) +".meta";
					stat(MetaName.c_str(),&st);
					sHeader.DataLength += st.st_size;
				}
				memcpy(&StatusMsg[23],&sHeader.DataLength,4);
				   //----------------------------------------- SENDING MESSAGE ------------------------------------- BEGIN--//
				   for (unsigned int it = 0;it<27 ;it++ )
					{
							if (write(mySocket,&StatusMsg[it],1)==-1)
								{
								//	perror("beaconconnect: write");
									exit(1);
								}
					}
				memcpy(&StatusMsg[27],fd_obj->respUOID,20);
				memcpy(&StatusMsg[47],&HostInfoLength,2);
				memcpy(&StatusMsg[49],&HostPort,2);
				memcpy(&StatusMsg[51],&hostname,13);
				   for (unsigned int it = 27;it<64 ;it++ )
					{
							if (write(mySocket,&StatusMsg[it],1)==-1)
								{
								//	perror("beaconconnect: write");
									exit(1);
								}
					}			
				for(elem=nameList->First();elem!=NULL;elem=nameList->Next(elem))
				{

					string NodeHome = (string(HomeDir1)).substr(0,(int)strlen(HomeDir1)-1);
					string FilesHome = NodeHome + "/files";
					int LocalIndex=((Boot_Elem*)(elem->Obj()))->index; 
					char myCurrName[100];
					sprintf(myCurrName,"%d",LocalIndex);
					string MetaName = FilesHome +"/"+string(myCurrName) +".meta";
					stat(MetaName.c_str(),&st);
				   //---------------sending Metafile--------------BEGIN------------//
					FILE *pf1 = fopen(((string(MetaName)).c_str()),"r");
					unsigned int metacount = (unsigned int)(st.st_size)/8192;
					unsigned int actsize = st.st_size;
					pthread_mutex_lock(&PrintLock);
					//cout<<"DataLength: "<<sHeader.DataLength<<endl;
					//cout<<"MetaSize: "<<st.st_size<<endl;
					pthread_mutex_unlock(&PrintLock);
					//----------------------------- record length ----------//
									   unsigned char* LenBuf = (unsigned char*)malloc(4);
					   memset(LenBuf,0,4);
					   memcpy(&LenBuf[0],&(st.st_size),4);
						for (unsigned int it = 0;it<4;it++)
						{
							if (write(mySocket,&LenBuf[it],1)==-1)
								{
									//perror("beaconconnect: write");
					//				cout<<"CheckWrite1:"<<errno<<endl; 
							//		exit(1);
								}

						}//count for loop

					//---------------------------------------- end record length//
					if (metacount>=1 && (st.st_size%8192)!=0){
						metacount=metacount+1;
					}else{
						if (metacount==0)
						{
							metacount=1;
						}else{
							metacount=st.st_size/8192;
						}
					}
					   unsigned int buf_count =0;
					   for(unsigned int icount=0;icount<metacount;icount++){

						   if(actsize>=8192){
							   buf_count=8192;
						   }else{
							   buf_count=actsize;
						   }
						   actsize = actsize - 8192;
						unsigned char* MsgBuf = (unsigned char*)malloc(8192);
					   size_t bytes_read;
						
					   memset(MsgBuf,0,8192);
					  
						bytes_read=0;
					   bytes_read = fread(MsgBuf,1,buf_count,pf1);
					   	pthread_mutex_lock(&PrintLock);
					//	cout<<MsgBuf<<endl;
						pthread_mutex_unlock(&PrintLock);
						for (unsigned int it = 0;it<bytes_read ;it++)
						{
							if (write(mySocket,&MsgBuf[it],1)==-1)
								{
									//perror("beaconconnect: write");
					//				cout<<"CheckWrite1:"<<errno<<endl; 
							//		exit(1);
								}

						}
				//		cout<<"Bytes sent: "<<bytes_read<<endl;
				   buf_count=0;
				   free(MsgBuf);
				   }
				   fclose(pf1);

				   //---------------sending Metafile--------------END------------//				}

			}//end for loop
		}//end if namelist!=0
//		cout<<"DataLength: "<<sHeader.DataLength<<endl;
		}
	}//if strs
 	//------------------------------------------------------------------------------STRS -----------------------------END---------//

	//------------------------------------------------------------------------------STRQ ------------------------------BEGIN------//

	if(fd_obj->MessageType==STRQ)
	{
		struct HEADER sHeader;
//		cout<<"Write status thread"<<endl;
		sHeader.MessageType = STRQ;
        sHeader.UOID = new unsigned char[20];
		for(int it2=0;it2<20;it2++){
					sHeader.UOID[it2]=fd_obj->UOID[it2];
				}
		
		sHeader.TTL = (unsigned char)(fd_obj->TTL);
		sHeader.Reserved = (unsigned char)0;
		sHeader.DataLength = 1;
//		cout<<"Temp: "<<Gelem->Temp<<endl;
		struct STATUS_MSG sMsg;
		if (fd_obj->Distance==2)
		{
			sMsg.StatusType=neighbors;
		}else if (fd_obj->Distance==8)
		{
			sMsg.StatusType=files;
//			cout<<"Status type files"<<endl;
		}

		//if(fd_obj->flag==1){sMsg.StatusType=neighbors;}else{sMsg.StatusType=files;}
		if (sHeader.TTL!=0)
		{
		
		unsigned char* StatusMsg = new unsigned char[512];
		memcpy(&StatusMsg[0],&sHeader.MessageType,1);
		memcpy(&StatusMsg[1],sHeader.UOID,20);
		memcpy(&StatusMsg[21],&sHeader.TTL,1);
		memcpy(&StatusMsg[22],&sHeader.Reserved,1);
		memcpy(&StatusMsg[23],&sHeader.DataLength,4);
		memcpy(&StatusMsg[27],&sMsg.StatusType,1);

		for (int it = 0;it<27 ;it++ )
			{
				if (write(mySocket,&StatusMsg[it],1)==-1)
					{
					//	perror("beaconconnect: write");
						exit(1);
					}
			}
			for (int it5 = 27;it5<28; it5++ )
			{
				if (write(mySocket,&StatusMsg[it5],1)==-1)
				{
		//			perror("beaconconnect: write");
					exit(1);
				}	
			}

			
	    //---------------------------------------------- RESET----------------------------------------------------//
		pthread_mutex_lock(&log_lock);
		FILE *Log = fopen(LogLocation.c_str(),"a");
		if(Log==NULL)
		{
		cerr<<"Log file can not be opened. The program will continue without logging."<<endl;
		}else{
		gettimeofday(&tim,NULL);
		fprintf(Log,"f %10ld.%03d nunki.usc.edu_%d STRQ %d ",(tim.tv_sec),(int)((tim.tv_usec)/1000),ntohs(peer.sin_port),(int)(sHeader.TTL));
		for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(sHeader.UOID)[pr]);}
		fprintf(Log," neighbors\n");
		fflush(Log);
		}
		fclose(Log);
		pthread_mutex_unlock(&log_lock);
		//---------------------------------------------------------------------------------------------------------//
			pthread_mutex_lock(&PrintLock);
	//		cout<<"STRQ UOID: ";
			for(int it2=0;it2<20;it2++){
						//printf("%02x",(unsigned char)(fd_obj->UOID)[it2]);
				}
				//cout<<endl;
				
		//	cout<<"STRQ flooded to "<<Gelem->Port<<endl;
		
			pthread_mutex_unlock(&PrintLock);

		}
	}
		
    //------------------------------------------------------------------------------STRQ ------------------------------END--------//	
	if(fd_obj->MessageType==JNRQ)
	{
/*			
	//-----------------------------TESTING--------------------------BEGIN------//
		pthread_mutex_lock(&PrintLock);
		cout<<"JNRQ in the write thread"<<endl; 
		cout<<"Port inside write "<<fd_obj->Port<<endl;
		cout<<"TTL inside write "<<(int)fd_obj->TTL<<endl;
		cout<<"Host Location inside write "<<fd_obj->HostLocation<<endl;
		cout<<"UOID inside write ";
		for(int it2=0;it2<20;it2++){
						printf("%02x",(unsigned char)(fd_obj->UOID)[it2]);
				}cout<<endl;
		pthread_mutex_unlock(&PrintLock);
		//-----------------------------TESTING--------------------------END------//
*/		
		if ((int)fd_obj->TTL !=0)
		{

			unsigned char *writeBuf = new unsigned char[512];
			unsigned char Reserved = (unsigned char)0;
			unsigned int DataLength = 19;
			memcpy(&writeBuf[0],&(fd_obj->MessageType),1);
			memcpy(&writeBuf[1],fd_obj->UOID,20);
			memcpy(&writeBuf[21],&(fd_obj->TTL),1);
			memcpy(&writeBuf[22],&Reserved,1);
			memcpy(&writeBuf[23],&DataLength,4);
			memcpy(&writeBuf[27],&(fd_obj->HostLocation),4);
			memcpy(&writeBuf[31],&(fd_obj->Port),2);
			memcpy(&writeBuf[33],&hostname,13);
			
			for (int it = 0;it<27 ;it++ )
			{
				if (write(mySocket,&writeBuf[it],1)==-1)
					{
				//		perror("beaconconnect: write");
						exit(1);
					}
			}
			for (int it5 = 27;it5<27+19; it5++ )
			{
				if (write(mySocket,&writeBuf[it5],1)==-1)
				{
			//		perror("beaconconnect: write");
					exit(1);
				}	
			}
        //---------------------------------------------- RESET----------------------------------------------------//
		pthread_mutex_lock(&log_lock);
		FILE *Log = fopen(LogLocation.c_str(),"a");
		if(Log==NULL)
		{
		cerr<<"Log file can not be opened. The program will continue without logging."<<endl;
		}else{
		gettimeofday(&tim,NULL);
		fprintf(Log,"f %10ld.%03d nunki.usc.edu_%d JNRQ %d ",(tim.tv_sec),(int)((tim.tv_usec)/1000),ntohs(peer.sin_port),(int)(fd_obj->TTL));
		for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(fd_obj->UOID)[pr]);}
		fprintf(Log," %d nunki.usc.ed\n",fd_obj->Port);
		fflush(Log);
		}
		fclose(Log);
		pthread_mutex_unlock(&log_lock);
		//---------------------------------------------------------------------------------------------------------//
          

		}else{
		//	cout<<"TTL is ZERO"<<endl; //exit(1);
		}
	}//END IF MSG TYPE = JNRQ
	else if(fd_obj->MessageType == JNRS){
		if ((int)fd_obj->TTL !=0)
		{

			unsigned char *writeBuf1 = new unsigned char[512];
			unsigned char Reserved = (unsigned char)0;

			unsigned int DataLength = 39;
						
			memcpy(&writeBuf1[0],&(fd_obj->MessageType),1);
			memcpy(&writeBuf1[1],fd_obj->respUOID,20);
			memcpy(&writeBuf1[21],&(fd_obj->TTL),1);
			memcpy(&writeBuf1[22],&Reserved,1);
			memcpy(&writeBuf1[23],&DataLength,4);
			memcpy(&writeBuf1[27],fd_obj->UOID,20);
			memcpy(&writeBuf1[47],&(fd_obj->Distance),4);
			memcpy(&writeBuf1[51],&(fd_obj->respPort),2);
			memcpy(&writeBuf1[53],&hostname,13);
			for (int it = 0;it<27 ;it++ )
			{
				if (write(mySocket,&writeBuf1[it],1)==-1)
					{
						//perror("beaconconnect: write");
						exit(1);
					}
			}
			for (int it5 = 27;it5<27+39; it5++ )
			{
				if (write(mySocket,&writeBuf1[it5],1)==-1)
				{
			//		perror("beaconconnect: write");
					exit(1);
				}	
			}

	    //---------------------------------------------- RESET----------------------------------------------------//
		pthread_mutex_lock(&log_lock);
		FILE *Log = fopen(LogLocation.c_str(),"a");
		if(Log==NULL)
		{
		cerr<<"Log file can not be opened. The program will continue without logging."<<endl;
		}else{
		gettimeofday(&tim,NULL);
		fprintf(Log,"s %10ld.%03d nunki.usc.edu_%d JNRS %d ",(tim.tv_sec),(int)((tim.tv_usec)/1000),ntohs(peer.sin_port),(int)(fd_obj->TTL));
		for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(fd_obj->respUOID)[pr]);}
		fprintf(Log," ");
		for(int pr=16;pr<20;pr++){fprintf(Log,"%02x",(fd_obj->UOID)[pr]);}
		fprintf(Log," %d %d nunki.usc.ed\n",fd_obj->Distance,fd_obj->respPort);
		fflush(Log);
		}
		fclose(Log);
		pthread_mutex_unlock(&log_lock);
		//---------------------------------------------------------------------------------------------------------//
		}
		}	
	}//end while
	pthread_exit(NULL);
}
//----------------------------------------- WRITE THREAD END ----------------------------------------------------//


